package com.moleq.mgpos.activities;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.R.integer;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.brother.ptouch.sdk.Printer;
import com.brother.ptouch.sdk.PrinterInfo;
import com.brother.ptouch.sdk.PrinterStatus;
import com.moleq.adapter.MixMatchSelectionAdapter;
import com.moleq.adapter.SelectionAdapter;
import com.moleq.base.MoleQBaseActivity;
import com.moleq.base.MoleQBaseDialog;
import com.moleq.device.DeviceManager;
import com.moleq.device.DeviceSettingService;
import com.moleq.device.ScannerSetting;
import com.moleq.dialog.AgeSelectionDialog;
import com.moleq.dialog.DateSettingSelectionDialog;
import com.moleq.dialog.InputDateInfoDialog;
import com.moleq.dialog.InputTimeInfoDialog;
import com.moleq.dialog.ItemDiscountDialog;
import com.moleq.dialog.MessageBox;
import com.moleq.dialog.MessageDialog;
import com.moleq.dialog.TimeSettingSelectionDialog;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.itemsetting.adapter.AgeAdapter;
import com.moleq.itemsetting.adapter.BottleAdapter;
import com.moleq.itemsetting.adapter.ImportTypeAdapter;
import com.moleq.itemsetting.adapter.ListAdapter;
import com.moleq.itemsetting.adapter.NetWTAdapter;
import com.moleq.itemsetting.adapter.ItemTareSelectionAdapter;
import com.moleq.itemsetting.adapter.PrinterAdapter;
import com.moleq.itemsetting.adapter.TareSelectionAdapter;
import com.moleq.itemsetting.models.ItemPic;
import com.moleq.itemsetting.tools.MGCreateFiles;
import com.moleq.itemsetting.tools.ReadFileTools;
import com.moleq.logic.MoleQConstants;
import com.moleq.logic.UPC;
import com.moleq.mgpos.widget.BeepImageButton;
import com.moleq.mgpos.widget.ScrollLayout;
import com.moleq.models.AdapterDataSourceBuilder;
import com.moleq.models.AgeSetting;
import com.moleq.models.BottleSetting;
import com.moleq.models.Departmant;
import com.moleq.models.FlipChart;
import com.moleq.models.GlobalInfo;
import com.moleq.models.ImportData;
import com.moleq.models.ItemDiscountSetting;
import com.moleq.models.ItemSetting;
import com.moleq.models.ItemSettingPrintTag;
import com.moleq.models.ItemTareSetting;
import com.moleq.models.MixMatch;
import com.moleq.models.MixMatch_detail;
import com.moleq.models.NetWT;
import com.moleq.models.PosSetting;
import com.moleq.models.PriceSetting;
import com.moleq.models.PrinterSetting;
import com.moleq.models.SubDepartmant;
import com.moleq.models.TareSetting;
import com.moleq.service.AgeSettingService;
import com.moleq.service.BottleSettingService;
import com.moleq.service.DepartmantService;
import com.moleq.service.FlipChartService;
import com.moleq.service.ItemPicService;
import com.moleq.service.ItemSettingService;
import com.moleq.service.ItemTareService;
import com.moleq.service.MixMatchService;
import com.moleq.service.MixMatchSettingService;
import com.moleq.service.NetWTService;
import com.moleq.service.PriceService;
import com.moleq.service.PrinterSettingService;
import com.moleq.service.ServiceManager;
import com.moleq.service.SubDepartmantService;
import com.moleq.service.TareSettingService;
import com.moleq.util.ChangeMode;
import com.moleq.util.EditTextMaxLengthWatcher;
import com.moleq.util.ImageUtil;
import com.moleq.util.MoleQUtil;

public class ItemSettingActivity extends MoleQBaseActivity {
	private List<ItemSetting> listitem = null;
	private ListView list = null, lv_tare;
	private List<NetWT> NetWTList = null;
	private List<SubDepartmant> DeptList = null;
	private List<TareSetting> tareSettingList = null;
	private List<ItemTareSetting> itemTareList = null;
	private List<BottleSetting> bottleList = null;
	private List<AgeSetting> ageList = null;
	private List<PrinterSetting> printerList = null;
	private ListAdapter listAdapter;
	private NetWTAdapter netWTAdapter;
	private SelectionAdapter deptAdapter;
	private AgeAdapter ageAdapter;
	private SelectionAdapter tareChooseAdapter = null;
	private TareSelectionAdapter tareSettingAdapter = null;
	private ItemTareSelectionAdapter tareSelectionAdapter = null;
	private BottleAdapter bottleAdapter = null;
	private PrinterAdapter printerAdapter = null;
	private Spinner sp_list;
	private String PathString = "";
	private int PageCountSize = 0;
	private EditText et_upc, et_name, et_desc, et_price, et_price_2, et_wt;
	private EditText et_vdr, et_sub_dept, et_case_pack_size, et_search,
			et_case_cost, et_net_wt_search;
	private CheckBox cb_active, cb_food_stamp, cb_scale_weight, cb_wic, cb_cvv,
			cb_tax_1, cb_tax_2, cb_tax_3, cb_tax_4, cb_tax_5, cb_tax_6,
			cb_follow_dept, cb_no_discnt, cb_bottle_deposit, cb_loyalty,
			cb_age_ver, cb_coupon, cb_printer, cb_mult_coupon;
	private Button btn_del, btn_add, btn_search, btn_undo, btn_save, btn_exit,
			btn_net_wt, btn_dep, btn_tare, btn_single_tare, btn_bottle_deposit,
			btn_age_ver, btn_import, btn_printer;
	private ImageButton btn_next, btn_back;
	private TextView tv_page, tv_tare_background,tv_send_to_printer;
	private ImageView iv_photo, iv_price_setting, iv_add, iv_del;
	private BeepImageButton	iv_tare_del,iv_tare_add;
	private String filePathString = "", disLink = "";
	private String searchString = "";
	private String imagePath = "";
	private String SaveMode = "";
	private int searchType = 0;
	private ArrayList<String> tareItems;
	private String[] sp_items;
	private ScrollLayout scrollLayout;
	private AbsoluteLayout al, al2, al_price_detail;
	private DeviceSettingService mDeviceSettingService;
	private PriceService mPriceService;
	private ItemSettingService mItemSettingService;
	private DepartmantService mDepartmantService;
	private MixMatchService mMixMatchService;
	private MixMatchSettingService mMixMatchSettingService;
	private AgeSettingService mAgeSettingService;
	private SubDepartmantService mSubDepartmantService;
	private BottleSettingService mBottleSettingService;
	private TareSettingService mTareSettingService;
	private ItemPicService mItemPicService;
	private FlipChartService mFlipChartService;
	private ItemTareService mItemTareService;
	private NetWTService mNetWTService;
	private PrinterSettingService mPrinterSettingService;
	private static ItemDiscountSetting dis;
	private String price_type = "";
	private DeviceManager mDeviceManager;
	static final int DATE_DIALOG_ID_S = 0;
	static final int DATE_DIALOG_ID_E = 1;
	static final int TIME_DIALOG_ID_S = 2;
	static final int TIME_DIALOG_ID_E = 3;
	private int mYear, mMonth, mDay, hour, minute1;
	private String datetype, timetype;
	private Boolean isDelete = false, isImg = false, is_age_edit = false,
			is_import_data = false, isImport = false;;
	protected static final int GUI_STOP_NOTIFIER = 0;
	protected static final int GUI_THREADING_NOTIFIER = 1;
	private static ItemDiscountDialog mDisLinkItemDiscountDialog;
	private MGCreateFiles mMGCreateFiles = new MGCreateFiles();
	public static final int TARE_TYPE_NOTARE = 0;
	public static final int TARE_TYPE_SINGLETARE = 1;
	public static final int TARE_TYPE_MULTIPLETARE = 2;
	public AgeSelectionDialog ageDialog;
	
	private DateSettingSelectionDialog mdssDialog;
	private TimeSettingSelectionDialog tdssDialog;
	private InputTimeInfoDialog itidDialog;
	private InputDateInfoDialog ididDialog;
	
	Date now = new Date();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_item_setting);
		ControlFindId();
		// =========== setup scanner =================
		mDeviceManager = DeviceManager.getInstance();
		mDeviceSettingService = ServiceManager.getInstance().mDeviceSettingService;
		mItemSettingService = ServiceManager.getInstance().mItemSettingService;
		mPriceService = ServiceManager.getInstance().mPriceService;
		mMixMatchService = ServiceManager.getInstance().mMixMatchService;
		mDepartmantService = ServiceManager.getInstance().mDepartmantService;
		mAgeSettingService = ServiceManager.getInstance().mAgeSettingService;
		mMixMatchSettingService = ServiceManager.getInstance().mMixMatchSettingService;
		mSubDepartmantService = ServiceManager.getInstance().mSubDepartmantService;
		mItemPicService = ServiceManager.getInstance().mItemPicService;
		mFlipChartService = ServiceManager.getInstance().mFlipChartService;
		mTareSettingService = ServiceManager.getInstance().mTareSettingService;
		mBottleSettingService = ServiceManager.getInstance().mBottleSettingService;
		mItemTareService = ServiceManager.getInstance().mItemTareService;
		mNetWTService = ServiceManager.getInstance().mNetWTService;
		List<ScannerSetting> scannerSettings = mDeviceSettingService
				.getScannerSettings();
		mPrinterSettingService = ServiceManager.getInstance().mPrinterSettingService;
		// check scanner
		int iScannerCount = scannerSettings.size();
		for (int i = 0; i < iScannerCount; i++) {
			int iPort = scannerSettings.get(i).getPort();
			for (int j = i + 1; j < iScannerCount; j++) {
				if (iPort == scannerSettings.get(j).getPort()) {
					MessageBox.show(ItemSettingActivity.this,
							"Scanner setup error. Please check.",
							onClickMessageListener,
							MessageDialog.MESSAGE_BOX_OK);
					finish();
				}

			}
		}
		mDeviceManager.setDeviceCallbackEvent(this);
		mDeviceManager.setScannerSettingLists(scannerSettings);
		mDeviceManager.buildAllScanner();
		mDeviceManager.connectAllScanner();
		mDeviceManager.enableAllScanner();
		// ============================================
		sp_items = getResources().getStringArray(R.array.sp_itemsname);
		ArrayAdapter<String> SpAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, sp_items);
		SpAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_list.setAdapter(SpAdapter);
		sp_list.setOnItemSelectedListener(onItemSelectedListener);
		SetNetWTDataSource("");
		SetDepartment();
		btn_back.setOnClickListener(onClickListener);
		btn_next.setOnClickListener(onClickListener);
		btn_search.setOnClickListener(onClickListener);
		btn_add.setOnClickListener(onClickListener);
		btn_del.setOnClickListener(onClickListener);
		btn_save.setOnClickListener(onClickListener);
		btn_undo.setOnClickListener(onClickListener);
		btn_exit.setOnClickListener(onClickListener);
		btn_import.setOnClickListener(onClickListener);
		cb_active.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_follow_dept.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_tax_1.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_tax_2.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_tax_3.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_tax_4.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_tax_5.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_tax_6.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_bottle_deposit.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_printer.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_mult_coupon.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_loyalty.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_no_discnt.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_food_stamp.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_scale_weight.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_age_ver.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_wic.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_cvv.setOnCheckedChangeListener(onCheckedChangeListener);
		cb_coupon.setOnCheckedChangeListener(onCheckedChangeListener);
		btn_net_wt.setOnClickListener(onClickListener);
		btn_dep.setOnClickListener(onClickListener);
		btn_tare.setOnClickListener(onClickListener);
		iv_price_setting.setOnClickListener(onClickListener);
		iv_add.setOnClickListener(onClickListener);
		iv_del.setOnClickListener(onClickListener);
		btn_single_tare.setOnClickListener(onClickListener);
		lv_tare.setOnItemClickListener(onItemClickListener);
		btn_bottle_deposit.setOnClickListener(onClickListener);
		btn_printer.setOnClickListener(onClickListener);
		btn_age_ver.setOnClickListener(onClickListener);
		iv_photo.setOnClickListener(onClickListener);
		al.setOnClickListener(onClickListener);
		al2.setOnClickListener(onClickListener);
		
		mdssDialog = new DateSettingSelectionDialog(this);
		tdssDialog = new TimeSettingSelectionDialog(this);
		itidDialog = new InputTimeInfoDialog(this, this);
		ididDialog = new InputDateInfoDialog(this, this);

//		GlobalInfo.getInstance().calendar_type = ServiceManager.getInstance().mPosSettingService.Find().isCalendarType();

		PosSetting item = ServiceManager.getInstance().mPosSettingService.Find();
		if(item == null){
			GlobalInfo.getInstance().calendar_type = false;
		}else{
			GlobalInfo.getInstance().calendar_type = item.isCalendarType();
		}
		
		SetTextChange();
		InitializeEnabledFalse();
		if (itemTareList == null) {
			itemTareList = new ArrayList<ItemTareSetting>();
		}
		if (tareSelectionAdapter == null) {
			tareSelectionAdapter = new ItemTareSelectionAdapter(this, itemTareList);
		}
		lv_tare.setAdapter(tareSelectionAdapter);
		SetTareSetting();
		SetBottleDeposit();
		SetPrinterSetting();
		ageList = mAgeSettingService.FindAll();
		
	}

	public OnItemSelectedListener onItemSelectedListener = new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> parent, View View,
				int position, long id) {
			// TODO Auto-generated method stub
			if (sp_items[position].equals("ALL")) {
				et_search.setEnabled(false);
				et_search.clearFocus();
			} else {
				et_search.setEnabled(true);
				et_search.requestFocus();
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		}
	};

	public OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub

			switch (parent.getId()) {
			case R.id.lv_listitem:
				ChangeMode.mode = 0;
				Keyboard();
				listAdapter.ScrollToRow(position);
				String upc = String.valueOf(listitem.get(position).getUpc());
				itemTareList.clear();
				btn_single_tare.setText("");
				GetItemDetail(upc);
				tareSelectionAdapter.ScrollToRow(0);
				SetCouponStatus(cb_coupon.isChecked());
				ChangeMode.mode = 1;
				break;
			case R.id.lv_net_wt_list:
				ChangeMode.mode = 0;
				netWTAdapter.ScrollToRow(position);
				ChangeMode.mode = 1;
				break;
			case R.id.lv_dept_list:
				ChangeMode.mode = 0;
				deptAdapter.ScrollToRow(position);
				ChangeMode.mode = 1;
				break;
			case R.id.lv_tare_list:
				ChangeMode.mode = 0;
				tareChooseAdapter.ScrollToRow(position);
				ChangeMode.mode = 1;
				break;
			case R.id.lv_tare_setting_list:
				ChangeMode.mode = 0;
				tareSettingAdapter.ScrollToRow(position);
				ChangeMode.mode = 1;
				break;
			case R.id.lv_tare:
				ChangeMode.mode = 0;
				tareSelectionAdapter.ScrollToRow(position);
				ChangeMode.mode = 1;
				break;
			case R.id.lv_bottle_deposit_list:
				ChangeMode.mode = 0;
				bottleAdapter.ScrollToRow(position);
				ChangeMode.mode = 1;
				break;
			case R.id.lv_printer_list:
				ChangeMode.mode = 0;
				printerAdapter.ScrollToRow(position);
				ChangeMode.mode = 1;
				break;
			case R.id.lv_age_dialog_list:
				ChangeMode.mode = 0;
				ageAdapter.ScrollToRow(position);
				ChangeMode.mode = 1;
				break;
			case R.id.lv_import_type_list:
				importTypeAdapter.ScrollToRow(position);
				break;
			}
		}
	};
	OnClickListener onClickListener = new OnClickListener() {
		String sql = "";
		String pagetext = "";
		int page;
		String upc = "";

		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.btn_search:
				ChangeMode.mode = 0;
				Keyboard();
				tv_page.setText(String.valueOf(1));
				Search();
				ChangeMode.mode = 1;
				break;
			case R.id.btn_back:
				btn_back.setEnabled(false);
				pagetext = (String) tv_page.getText();
				page = Integer.valueOf(pagetext);
				tv_page.setText(String.valueOf(page - 1));
				SetPage();
				BindingData((page - 2), searchType, searchString);
				RefresItem();
				list.setSelection(0);
				btn_back.setEnabled(true);
				break;
			case R.id.btn_next:
				btn_next.setEnabled(false);
				pagetext = (String) tv_page.getText();
				page = Integer.valueOf(pagetext);
				tv_page.setText(String.valueOf(page + 1));
				SetPage();
				BindingData(page, searchType, searchString);
				RefresItem();
				list.setSelection(0);
				btn_next.setEnabled(true);
				break;
			case R.id.btn_add:
				
				if (GlobalInfo.getInstance().isDemoVersion) {
					if (mItemSettingService.getItemCount() >= 100) {
						MessageBox.show(ItemSettingActivity.this, "No more item can be added in this version.");
						return;
					}
				}
				
				itemTareList.clear();
				tareSelectionAdapter.setSource(itemTareList);
				tareSelectionAdapter.notifyDataSetChanged();
				InitializeEnabledTrue();
				SetEnabledFalse();
				ControlEmpty();
				et_upc.setEnabled(true);
				cb_active.setChecked(true);
				et_upc.requestFocus();
				if (DeptList.size() <= 0) {
					btn_dep.setText(String.valueOf("1"));
				} else {
					btn_dep.setText(String
							.valueOf(DeptList.get(0).getSd_name()));
				}
				scrollLayout.setToScreen(0);
				cb_follow_dept.setEnabled(false);
				cb_follow_dept.setChecked(true);
				cb_coupon.setEnabled(false);
				FollowDeptCheckedTrue();
				if (listitem != null && listitem.size() > 0) {
					listitem.clear();
					listAdapter.setSource(listitem);
					listAdapter.notifyDataSetChanged();
				}
				btn_exit.setEnabled(true);
				btn_tare.setText("No");
				TareImageView("No");
				btn_single_tare.setText("");
				itemTareList.clear();
				SaveMode = "Insert";
				break;
			case R.id.btn_delete:
				Keyboard();
				if (listAdapter.GetSelectedIndex() < 0)
					return;
				String upc = String.valueOf(listitem.get(
						listAdapter.GetSelectedIndex()).getUpc());
				int setting = 0;
				setting += mItemSettingService.CheckMMSetting(upc);
				setting += mItemSettingService.CheckFCSetting(upc);
				setting += mItemSettingService.CheckPriceSetting(upc);
				setting += mItemSettingService.CheckTareSetting(upc);
				isDelete = true;
				if (setting > 0) {
					MessageBox
							.show(ItemSettingActivity.this,
									"The item is linked with many setting. Do you still want to delete it?",
									onClickMessageListener,
									MessageDialog.MESSAGE_BOX_YES_NO);
				} else {
					MessageBox.show(ItemSettingActivity.this,
							"Are you sure to delete this item?",
							onClickMessageListener,
							MessageDialog.MESSAGE_BOX_YES_NO);
				}
				break;
			case R.id.btn_save:
				ChangeMode.mode = 0;
				Save();
				ChangeMode.mode = 1;
				Keyboard();
				break;
			case R.id.btn_undo:
				if (listitem != null) {
					if (listitem.size() > 0) {

						int index = listAdapter.GetSelectedIndex();
						int size = listitem.size();
						itemTareList.clear();
						btn_single_tare.setText("");
						if (index >= 0 && size > 0) {
							upc = String.valueOf(listitem.get(index).getUpc());
							ChangeMode.mode = 0;
							GetItemDetail(upc);
							ChangeMode.mode = 1;
						}
						et_upc.setEnabled(false);
						SetEnabledTrue();
						SetPage();
						cb_follow_dept.setEnabled(true);
						cb_coupon.setEnabled(true);
					} else {
						ControlEmpty();
						SetEnabledTrue();
						FollowDeptCheckedTrue();
						InitializeEnabledFalse();
					}
				} else {
					ControlEmpty();
					SetEnabledTrue();
					FollowDeptCheckedTrue();
					InitializeEnabledFalse();
				}
				et_price.setTag(0);
				et_price_2.setTag(0);
				SaveMode = "";
				break;
			case R.id.btn_exit:
				MessageBox.show(ItemSettingActivity.this, getResources()
						.getString(R.string.msg_exit_program),
						onClickMessageListener,
						MessageDialog.MESSAGE_BOX_YES_NO);
				break;
			case R.id.iv_photo:
				if (listAdapter == null)
					break;
				if (listAdapter.GetSelectedIndex() == -1)
					break;
				if (listitem.size() <= 0)
					break;
				ImageWindow();
				break;
			case R.id.btn_unit_of_measure:
				NetWTWindow();
				break;
			case R.id.btn_dep:
				DeptWindow();
				break;
			case R.id.btn_tare:
				TareChooseWindow();
				break;
			case R.id.al_one:
				Keyboard();
				break;
			case R.id.al_two:
				Keyboard();
				break;
			case R.id.ll_price_detail:
				InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				inputMethodManager.hideSoftInputFromWindow(priceDialog
						.getWindow().getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
				break;
			case R.id.iv_price_setting:
				upc = et_upc.getText().toString();
				if (upc.trim().length() <= 0 || upc == null)
					return;
				PriceSettingWindow(upc);
				break;
			case R.id.ibtn_clear_date:
				et_et_date.setText("");
				et_et_time.setText("");
				et_st_date.setText("");
				et_st_time.setText("");
				break;
			case R.id.ibtn_clear_mm:
				btn_mm = (Button) priceDialog.findViewById(R.id.btn_mm);
				btn_mm.setText("");
				break;
			case R.id.btn_mm:
				if (cb_follow_dept.isChecked()) {
					String depString = btn_dep.getText().toString();
					int depNo = 1;
					if (DeptList.size() <= 0) {
						depNo = 1;
					} else {
						for (int i = 0; i < DeptList.size(); i++) {
							if (depString.equals(DeptList.get(i).getSd_name())) {
								depNo = Integer.valueOf(DeptList.get(i)
										.getSd_id());
							} else {
								depNo = 1;
							}
						}
					}
					Departmant deps = mDepartmantService.Find(depNo);
					if (deps != null) {
						if (deps.getScale_weight()) {
							MessageBox
									.show(ItemSettingActivity.this,
											"A scalable item cannot be added into a mix match group.",
											onClickMessageListener,
											MessageDialog.MESSAGE_BOX_OK);
							return;
						}
					}
				} else {
					if (cb_scale_weight.isChecked()) {
						MessageBox
								.show(ItemSettingActivity.this,
										"A scalable item cannot be added into a mix match group.",
										onClickMessageListener,
										MessageDialog.MESSAGE_BOX_OK);
						return;
					}
				}
				ScaleControlID = R.id.btn_mm;
				DialogWindows();
				break;
			case R.id.iv_tare_add:
				SetEnabledFalse();
				if (SaveMode != "Insert") {
					SaveMode = "Update";
				}
				TareSettingWindow();
				break;
			case R.id.iv_tare_del:
				SetEnabledFalse();
				if (SaveMode != "Insert") {
					SaveMode = "Update";
				}
				if (itemTareList.size() > 0) {
					int index = tareSelectionAdapter.GetSelectedIndex();
					int index2 = -1;
					if (index == 0 && itemTareList.size() > 1) {
						index2 = index;
					} else if (index > 0) {
						index2 = index - 1;
					}
					itemTareList
							.remove(tareSelectionAdapter.GetSelectedIndex());
					tareSelectionAdapter.setSource(itemTareList);
					tareSelectionAdapter.notifyDataSetChanged();
					tareSelectionAdapter.ScrollToRow(index2);
				}
				break;
			case R.id.btn_single_tare:
				SetEnabledFalse();
				TareSettingWindow();
				break;
			case R.id.btn_bottle_deposit:
				SetEnabledFalse();
				if (SaveMode != "Insert") {
					SaveMode = "Update";
				}
				BottleWindow();
				break;
			case R.id.btn_printer:
				SetEnabledFalse();
				if (SaveMode != "Insert") {
					SaveMode = "Update";
				}
				PrinterWindow();
				break;
			case R.id.btn_age_ver:
				SetEnabledFalse();
				if (SaveMode != "Insert") {
					SaveMode = "Update";
				}
				ageDialog = new  AgeSelectionDialog(ItemSettingActivity.this);
				ageDialog.show(String.valueOf(btn_age_ver.getText()));
//				ageWindow();
				break;
			case R.id.btn_import:
				ImportItemWindow();
				break;
			case R.id.btn_dis_link:
				if (mDisLinkItemDiscountDialog == null
						|| mDisLinkItemDiscountDialog.isShowing())
					return;

				mDisLinkItemDiscountDialog.show();
				break;
			case R.id.ibtn_clear_dis_link:
				if (!btn_dis_link.getText().equals("")) {
					btn_dis_link.setText("");
					dis = null;
					disLink = "";
				}
				break;
			}
		}
	};

	OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			String upc = et_upc.getText().toString();
			switch (buttonView.getId()) {
			case R.id.cb_follow_dept:
				if (isChecked) {
					FollowDeptCheckedTrue();
				} else {
					FollowDeptCheckedFalse();
				}
				break;
			case R.id.cb_bottle_deposit:
				if (isChecked) {
					btn_bottle_deposit.setText("");

					btn_bottle_deposit.setVisibility(View.VISIBLE);
				} else {
					btn_bottle_deposit.setVisibility(View.GONE);
				}
				break;
			case R.id.cb_age_ver:
				if (isChecked) {
					btn_age_ver.setVisibility(View.VISIBLE);
				} else {
					btn_age_ver.setText("");
					btn_age_ver.setTag(null);
					btn_age_ver.setVisibility(View.GONE);
				}
				break;
			case R.id.cb_coupon:
				SetCouponStatus(cb_coupon.isChecked());
				break;
			case R.id.cb_printer:
				if(isChecked){
					tv_send_to_printer.setVisibility(View.VISIBLE);
					btn_printer.setVisibility(View.VISIBLE);
				}else{
					tv_send_to_printer.setVisibility(View.GONE);
					btn_printer.setVisibility(View.GONE);
				}
				break;
			case R.id.cb_mult_coupon:
				
				break;
			default:
				break;
			}
			if (ChangeMode.mode == 1) {
				SetEnabledFalse();
				if (SaveMode != "Insert") {
					SaveMode = "Update";
				}
			}
		}
	};

	public void SetDepartment() {
		if (DeptList == null) {
			DeptList = new ArrayList<SubDepartmant>();
		} else {
			DeptList.clear();
		}
		DeptList = mSubDepartmantService.FindAll();
	}

	public String GetNetWT(String F23) {
		for (int i = 0; i < NetWTList.size(); i++) {
			NetWT netWT = NetWTList.get(i);
			if (netWT.getF23().equals(F23)) {
				return netWT.getUd_short();
			}
		}
		return "";
	}

	public int GetNetWTPosition(String ud_short) {
		for (int i = 0; i < NetWTList.size(); i++) {
			NetWT netWT = NetWTList.get(i);
			if (netWT.getUd_short().equals(ud_short)) {
				return i;
			}
		}
		return -1;
	}

	public int GetDeptPosition(String DeptName) {
		for (int i = 0; i < DeptList.size(); i++) {
			SubDepartmant dept = DeptList.get(i);
			if (dept.getSd_name().equals(DeptName)) {
				return i;
			}
		}
		return -1;
	}

	public int GetBottlePosition(String BottleName) {
		for (int i = 0; i < bottleList.size(); i++) {
			BottleSetting bottle = bottleList.get(i);
			if (bottle.getBo_desc().equals(BottleName)) {
				return i;
			}
		}
		return -1;
	}
	
	public int GetPrinterPosition(String PrinterName){
		for (int i = 0; i < printerList.size(); i++){
			PrinterSetting printer = printerList.get(i);
			if(printer.getPs_name().equals(PrinterName)){
				return i;
			}
		}
		return -1;
	}

	public int GetAgePosition(String AgeName) {
		for (int i = 0; i < ageList.size(); i++) {
			AgeSetting age = ageList.get(i);
			if (age.getAs_desc().equals(AgeName)) {
				return i;
			}
		}
		return -1;
	}

	public int GetTarePosition(String TareName) {

		if (TareName.equals("No")) {
			TareImageView("No");
			return 0;
		} else if (TareName.equals("Single")) {
			TareImageView("Single");
			return 1;
		} else if (TareName.equals("Multiple")) {
			TareImageView("Multiple");
			return 2;
		} else {
			TareImageView("No");
			return 0;
		}
	}

	public int GetItemTarePosition(String TareName) {
		if (tareSettingList.size() > 0) {
			for (int i = 0; i < tareSettingList.size(); i++) {
				if (TareName.equals(tareSettingList.get(i).getTa_desc())) {
					return i;
				}
			}
		}
		return 0;
	}

	public String GetNetWTF23(String ud_short) {
		for (int i = 0; i < NetWTList.size(); i++) {
			NetWT netWT = NetWTList.get(i);
			if (netWT.getUd_short().equals(ud_short)) {
				return netWT.getF23();
			}
		}
		return "00";
	}

	public void GetItemDetail(String upc) {
		ItemSetting itemSetting = mItemSettingService.findByUpc(upc);
		if (itemSetting != null) {
			et_upc.setText(itemSetting.getUpc());
			et_name.setText(itemSetting.getName());
			et_desc.setText(itemSetting.getDesc());
			if (itemSetting.getMultple() <= 1) {
				et_price.setText("");
			} else {
				et_price.setText(String.valueOf(itemSetting.getMultple()));
			}
			String price = String.format("%.2f", itemSetting.getPrice());
			et_price_2.setText(price);
			if (itemSetting.getWt() <= 0) {
				et_wt.setText("");
			} else {
				et_wt.setText(String.valueOf(itemSetting.getWt()));
			}
			btn_net_wt
					.setText(String.valueOf(GetNetWT(itemSetting.getNetWT())));
			cb_active.setChecked(itemSetting.getActiveCheckBox());
			btn_dep.setText("");
			if (DeptList.size() <= 0) {
				btn_dep.setText(String.valueOf(itemSetting.getDep()));
				btn_dep.setTag(String.valueOf(itemSetting.getDep()));
			} else {
				for (int i = 0; i < DeptList.size(); i++) {
					if (DeptList.get(i).getSd_id() == itemSetting.getDep()) {
						btn_dep.setText(DeptList.get(i).getSd_name());
						btn_dep.setTag(String.valueOf(itemSetting.getDep()));
					}
				}
				if (btn_dep.getText().toString().trim().equals("")) {
					btn_dep.setText(String.valueOf(itemSetting.getDep()));
				}
			}
			et_vdr.setText(itemSetting.getVendor());
			et_sub_dept.setText(String.valueOf(itemSetting.getSubDep()));
			et_case_pack_size
					.setText(String.valueOf(itemSetting.getCasePack()));
			et_case_cost.setText(String.valueOf(itemSetting.getCaseCost()));
			cb_tax_1.setChecked(itemSetting.getTax1CheckBox());
			cb_food_stamp.setChecked(itemSetting.getFoodStampCheckBox());
			cb_scale_weight.setChecked(itemSetting.getScaleWeightCheckBox());
			cb_wic.setChecked(itemSetting.getWicCheckBox());
			cb_cvv.setChecked(itemSetting.getCvvCheckBox());
			if (itemSetting.getFollowdepCheckBox()) {
				FollowDeptCheckedTrue();
			} else {
				FollowDeptCheckedFalse();
			}
			cb_follow_dept.setChecked(itemSetting.getFollowdepCheckBox());
			cb_tax_2.setChecked(itemSetting.getTax2CheckBox());
			cb_tax_3.setChecked(itemSetting.getTax3CheckBox());
			cb_tax_4.setChecked(itemSetting.getTax4CheckBox());
			cb_no_discnt
					.setChecked(itemSetting.getItem_discount_flagCheckBox());
			cb_bottle_deposit.setChecked(itemSetting
					.getBottle_depositCheckBox());
			if (itemSetting.getBottle_depositCheckBox()) {
				BottleSetting mBottleSetting = mBottleSettingService.Find(Integer.valueOf(itemSetting.getBottle_deposit()));
				if (mBottleSetting == null) {
					btn_bottle_deposit.setText("");
				}else {
					btn_bottle_deposit.setText(mBottleSetting.getBo_desc());
				}
				btn_bottle_deposit.setVisibility(View.VISIBLE);
			} else {
				btn_bottle_deposit.setVisibility(View.GONE);
			}
			cb_loyalty.setChecked(itemSetting.getIs_loyaltyCheckBox());
			if (itemSetting.getIs_tare() < 1) {
				btn_tare.setText("No");
				GetTarePosition("No");
			} else {
				switch (itemSetting.getIs_tare()) {
				case TARE_TYPE_NOTARE:
					btn_tare.setText("No");
					GetTarePosition("No");
					break;
				case TARE_TYPE_SINGLETARE:
					btn_tare.setText("Single");
					GetTarePosition("Single");
					btn_single_tare
							.setText(mItemTareService.GetSingleTare(upc));
					break;
				case TARE_TYPE_MULTIPLETARE:
					btn_tare.setText("Multiple");
					GetTarePosition("Multiple");
					itemTareList.clear();
					itemTareList = mItemTareService.GetMultipleTare(upc);
					tareSelectionAdapter.setSource(itemTareList);
					tareSelectionAdapter.notifyDataSetChanged();
					break;
				default:
					btn_tare.setText("No");
					GetTarePosition("No");
					break;
				}
			}
			if (itemSetting.getIs_age_verCheckBox()) {
				btn_age_ver.setVisibility(View.VISIBLE);
				AgeSetting ageSetting = mAgeSettingService.Find(Integer
						.valueOf(itemSetting.getIs_age_ver()));
				if (ageSetting != null) {
					btn_age_ver.setText(ageSetting.getAs_desc());
					btn_age_ver.setTag(ageSetting);
				}else{
					btn_age_ver.setText("");
				}
				
			}
			cb_age_ver.setChecked(itemSetting.getIs_age_verCheckBox());
			cb_tax_5.setChecked(itemSetting.getTax5CheckBox());
			cb_tax_6.setChecked(itemSetting.getTax6CheckBox());
			cb_coupon.setChecked(itemSetting.getIs_couponCheckBox());
			Bitmap bp = mItemPicService.getImageByUPC(upc);
			if (bp == null) {
				Bitmap logo = BitmapFactory.decodeResource(ItemSettingActivity.this
						.getApplicationContext().getResources(),
						R.drawable.moleqlogo);
				iv_photo.setImageBitmap(logo);
			} else {
				iv_photo.setImageBitmap(bp);
			}
			if (!isDelete) {
				listitem.set(listAdapter.GetSelectedIndex(), itemSetting);
				listAdapter.notifyDataSetChanged();
			}
			cb_printer.setChecked(itemSetting.getService_CheckBox());
			cb_mult_coupon.setChecked(itemSetting.getIs_mult_coupon_CheckBox());
			if(cb_printer.isChecked()){
				tv_send_to_printer.setVisibility(View.VISIBLE);
				btn_printer.setVisibility(View.VISIBLE);
			}else{
				tv_send_to_printer.setVisibility(View.GONE);
				btn_printer.setVisibility(View.GONE);
			}
			if(itemSetting.getPrinter_id() == null){
				btn_printer.setText("None");
			}else {
				if(printerList != null){
					for(int i = 0; i < printerList.size() ; i++){
						PrinterSetting item = printerList.get(i);
						if (item.getPs_id() == Integer.valueOf(itemSetting.getPrinter_id())) {
							btn_printer.setText(item.getPs_name());
							btn_printer.setTag(item);
						}
					}
				}else{
					btn_printer.setText(itemSetting.getPrinter_id());
				}
			}
		}else{
			MessageBox
			.show(ItemSettingActivity.this,
					"Item Not Found.",
					onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return;
		}
	}

	public class SP {
		public static final int ALL = 0;
		public static final int UPC = 1;
		public static final int Department = 2;
		public static final int SubDept = 3;
		public static final int Vendor = 4;
	}

	public static boolean isNumeric(String str) {
		try {
			Double.valueOf(str);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	public String RoundUp(String value) {
		float f = Float.valueOf(value);
		f = Math.round(f * 100) / 100f;
		return String.valueOf(f);
	}

	public void Save() {
		String active;
		int follow_dept, tax1, tax2, tax3, tax4, tax5, tax6, no_discnt, food_stamp, scale_weight, wic, cvv, bottle_deposit, loyalty, age_ver, coupon;
		String upc = et_upc.getText().toString();
		String name = et_name.getText().toString();
		String desc = et_desc.getText().toString();
		String price = et_price.getText().toString();
		String price_2 = et_price_2.getText().toString();
		String wt = et_wt.getText().toString();
		String service_fl = "0",printer_id,mult_coupon = "0";
		wt = wt.trim();
		String wt_2 = GetNetWTF23(String.valueOf(btn_net_wt.getText()));
		if (cb_active.isChecked()) {
			active = "A";
		} else {
			active = "N";
		}
		String dep = btn_dep.getText().toString();
		if (DeptList.size() <= 0) {
			dep = "1";
		} else {
			for (int i = 0; i < DeptList.size(); i++) {
				if (dep.equals(DeptList.get(i).getSd_name())) {
					dep = String.valueOf(DeptList.get(i).getSd_id());
				}
			}
		}
		String vdr = et_vdr.getText().toString();
		String sub_dept = et_sub_dept.getText().toString();
		String case_pack_size = et_case_pack_size.getText().toString();
		String case_cost = et_case_cost.getText().toString();
		int tare = GetTarePosition(btn_tare.getText().toString());
		if (cb_follow_dept.isChecked()) {
			follow_dept = 1;
		} else {
			follow_dept = 0;
		}
		if (follow_dept == 1) {
			tax1 = 0;
		} else {
			if (cb_tax_1.isChecked()) {
				tax1 = 1;
			} else {
				tax1 = 0;
			}
		}
		if (follow_dept == 1) {
			tax2 = 0;
		} else {
			if (cb_tax_2.isChecked()) {
				tax2 = 1;
			} else {
				tax2 = 0;
			}
		}
		if (follow_dept == 1) {
			tax3 = 0;
		} else {
			if (cb_tax_3.isChecked()) {
				tax3 = 1;
			} else {
				tax3 = 0;
			}
		}
		if (follow_dept == 1) {
			tax4 = 0;
		} else {
			if (cb_tax_4.isChecked()) {
				tax4 = 1;
			} else {
				tax4 = 0;
			}
		}
		if (follow_dept == 1) {
			tax5 = 0;
		} else {
			if (cb_tax_5.isChecked()) {
				tax5 = 1;
			} else {
				tax5 = 0;
			}
		}
		if (follow_dept == 1) {
			tax6 = 0;
		} else {
			if (cb_tax_6.isChecked()) {
				tax6 = 1;
			} else {
				tax6 = 0;
			}
		}
		if (follow_dept == 1) {
			no_discnt = 0;
		} else {
			if (cb_no_discnt.isChecked()) {
				no_discnt = 1;
			} else {
				no_discnt = 0;
			}
		}
		if (follow_dept == 1) {
			food_stamp = 0;
		} else {
			if (cb_food_stamp.isChecked()) {
				food_stamp = 1;
			} else {
				food_stamp = 0;
			}
		}
		if (follow_dept == 1) {
			scale_weight = 0;
		} else {
			if (cb_scale_weight.isChecked()) {
				scale_weight = 1;
			} else {
				scale_weight = 0;
			}
		}
		if (follow_dept == 1) {
			age_ver = 0;
		} else {
			if (cb_age_ver.isChecked()) {
				if (String.valueOf(btn_age_ver.getText()).equals("")) {
					MessageBox.show(ItemSettingActivity.this,
							"Please select a age.", onClickMessageListener,
							MessageDialog.MESSAGE_BOX_OK);
					return;
				}
				AgeSetting as = (AgeSetting) btn_age_ver.getTag();
				if (mAgeSettingService.CheckAge(String.valueOf(as.getAs_no()))) {
					age_ver = 0;
				}else{
					age_ver = as.getAs_no();
				}
				
			} else {
				age_ver = 0;
			}
		}
		if (follow_dept == 1) {
			wic = 0;
		} else {
			if (cb_wic.isChecked()) {
				wic = 1;
			} else {
				wic = 0;
			}
		}
		if (follow_dept == 1) {
			cvv = 0;
		} else {
			if (cb_cvv.isChecked()) {
				cvv = 1;
			} else {
				cvv = 0;
			}
		}
		if (cb_loyalty.isChecked()) {
			loyalty = 1;
		} else {
			loyalty = 0;
		}
		if (cb_coupon.isChecked()) {
			coupon = 1;
			price = "1";
		} else {
			coupon = 0;
		}
		if (upc == null || upc == "" || upc.trim().length() <= 0) {
			MessageBox.show(ItemSettingActivity.this,
					"The upc can not be empty.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return;
		}
		if (name == null || name == "" || name.trim().length() <= 0) {
			MessageBox.show(ItemSettingActivity.this,
					"The name can not be empty.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return;
		}
		if (desc == null) {
			desc = "";
		}
		if (!isNumeric(price_2) || price_2 == null
				|| price_2.trim().length() <= 0) {
			MessageBox.show(ItemSettingActivity.this, "Please enter price.",
					onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
			return;
		}
		if (!price_2.equals("") && Double.valueOf(price_2) == 0 && !GlobalInfo.getInstance().isZeroPrice) {
			MessageBox.show(ItemSettingActivity.this, "Item Price cannot be zero.",
					onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
			return;
		}
		if (!isNumeric(wt) && !wt.equals("")) {
			MessageBox.show(ItemSettingActivity.this,
					"The Net WT Unit Price is not in the correct format.",
					onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
			return;
		}
		if (dep == null || dep == "" || dep.trim().length() <= 0) {
			MessageBox.show(ItemSettingActivity.this,
					"The Department can not be empty.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return;
		}
		if (cb_bottle_deposit.isChecked()) {
			if (String.valueOf(btn_bottle_deposit.getText()).trim().equals("")) {
				MessageBox.show(ItemSettingActivity.this,
						"Please select a bottle deposit.",
						onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
				return;
			}
			BottleSetting mBottleSetting = mBottleSettingService.Find(String
					.valueOf(btn_bottle_deposit.getText()));
			bottle_deposit = mBottleSetting.getBo_no();
		} else {
			bottle_deposit = 0;
		}
		if (mMixMatchService.checkMixMatch(upc) && cb_coupon.isChecked()) {
			MessageBox
					.show(ItemSettingActivity.this,
							"The item is linked with Mix Match Setting. Cannot change to coupon item. ",
							onClickMessageListener,
							MessageDialog.MESSAGE_BOX_OK);
			cb_coupon.setChecked(false);
			return;
		}
		if(cb_printer.isChecked()){
			service_fl = "1";
		}else{
			service_fl = "0";
		}
		if(cb_mult_coupon.isChecked()){
			mult_coupon = "1";
		}else{
			mult_coupon = "0";
		}
		if(btn_printer.getText().equals("None")){
			printer_id = "-1";
		}else{
			PrinterSetting temp = (PrinterSetting) btn_printer.getTag();
			if(temp == null){
				printer_id = null;
			}else{
				printer_id = String.valueOf(temp.getPs_id());
			}
			
		}
		PriceSetting mPriceSetting = null;
		mPriceSetting = mPriceService.getitempricesetting(upc);
		if (mPriceSetting != null) {
			if ((mPriceSetting.getStartdate() == null || mPriceSetting
					.getStartdate().trim().equals(""))
					&& (mPriceSetting.getStarttime() == null || mPriceSetting
							.getStarttime().trim().equals(""))
					&& (mPriceSetting.getEnddate() == null || mPriceSetting
							.getEnddate().trim().equals(""))
					&& (mPriceSetting.getEndtime() == null || mPriceSetting
							.getEndtime().trim().equals(""))
					&& (mPriceSetting.getPriceMultiple() == null || mPriceSetting
							.getPriceMultiple().trim().equals(""))
					&& (mPriceSetting.getPrice() == null || mPriceSetting
							.getPrice().trim().equals(""))
					&& (mPriceSetting.getPackagepricemultiple() == null || mPriceSetting
							.getPackagepricemultiple().trim().equals(""))
					&& (mPriceSetting.getPackageprice() == null || mPriceSetting
							.getPackageprice().trim().equals(""))
					&& (mPriceSetting.getLimitedqtyamount() == null || mPriceSetting
							.getLimitedqtyamount().trim().equals(""))
					&& (mPriceSetting.getLimitedqtyprice() == null || mPriceSetting
							.getLimitedqtyprice().trim().equals(""))
					&& (mPriceSetting.getDiscountamount() == null || mPriceSetting
							.getDiscountamount().trim().equals(""))
					&& (mPriceSetting.getDiscountpercent() == null || mPriceSetting
							.getDiscountpercent().trim().equals(""))
					&& (mPriceSetting.getPricemm() == null || mPriceSetting
							.getPricemm().trim().equals(""))
					&& (mPriceSetting.getDislink() == null || mPriceSetting
							.getDislink().trim().equals(""))
					&& cb_coupon.isChecked()) {
				mPriceService.DeletePriceSetting(upc);
				if (GlobalInfo.getInstance().isMGNetwork) {
					mMGCreateFiles
							.createrFile(mPriceSetting.toMGData("DELETE"));// UPDATE,DELETE
				}
			}
		}
		if (mMixMatchService.checkitemprice(upc) && cb_coupon.isChecked()) {
			MessageBox
					.show(ItemSettingActivity.this,
							"The item is linked with Price Setfting. Cannot change to coupon item. ",
							onClickMessageListener,
							MessageDialog.MESSAGE_BOX_OK);
			cb_coupon.setChecked(false);
			return;
		}
		switch (tare) {
		case 0:

			break;
		case 1:
			if (String.valueOf(btn_single_tare.getText()).trim().equals("")) {
				MessageBox.show(ItemSettingActivity.this,
						"Please select a tare.", onClickMessageListener,
						MessageDialog.MESSAGE_BOX_OK);
				return;
			}
			break;
		case 2:
			if (itemTareList.size() <= 0) {
				MessageBox.show(ItemSettingActivity.this,
						"Please select a tare.", onClickMessageListener,
						MessageDialog.MESSAGE_BOX_OK);
				return;
			}
			break;
		default:
			break;
		}
		ItemSetting itemSetting = new ItemSetting();
		itemSetting.setUpc(upc);
		itemSetting.setName(name);
		itemSetting.setDep(Integer.valueOf(dep));
		itemSetting.setSubDep(sub_dept);
		itemSetting.setActive(active);
		itemSetting.setCasePack(case_pack_size);
		itemSetting.setNetWT(wt_2);
		itemSetting.setWt(wt);
		itemSetting.setVendor(vdr);
		itemSetting.setDesc(desc);
		itemSetting.setPrice(Double.valueOf(price_2));
		itemSetting.setMultple(price);
		itemSetting.setCaseCost(case_cost);
		itemSetting.setFoodStamp(String.valueOf(food_stamp));
		itemSetting.setTax1(String.valueOf(tax1));
		itemSetting.setScaleWeight(String.valueOf(scale_weight));
		itemSetting.setWic(String.valueOf(wic));
		itemSetting.setCvv(String.valueOf(cvv));
		itemSetting.setFollowdep(String.valueOf(follow_dept));
		itemSetting.setTax2(String.valueOf(tax2));
		itemSetting.setTax3(String.valueOf(tax3));
		itemSetting.setTax4(String.valueOf(tax4));
		itemSetting.setItem_discount_flag(String.valueOf(no_discnt));
		itemSetting.setBottle_deposit(String.valueOf(bottle_deposit));
		itemSetting.setIs_loyalty(String.valueOf(loyalty));
		itemSetting.setIs_tare(tare);
		itemSetting.setIs_age_ver(String.valueOf(age_ver));
		itemSetting.setTax5(String.valueOf(tax5));
		itemSetting.setTax6(String.valueOf(tax6));
		itemSetting.setIs_coupon(String.valueOf(coupon));
		itemSetting.setService_fl(service_fl);
		itemSetting.setIs_mult_coupon(mult_coupon);
		if(printer_id.equals("-1")){
			itemSetting.setPrinter_id(null);
		}else{
			itemSetting.setPrinter_id(printer_id);
		}
		if (SaveMode == "Insert") {
			if (searchString.length() < 14) {
				UPC upc2 = new UPC(upc, UPC.INPUT_BY_MANUAL,
						GlobalInfo.getInstance().isNormalize);
				upc = upc2.code;
			} else {
				MessageBox.show(ItemSettingActivity.this, "Invalid upc code.",
						onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
				return;
			}
			if (mItemSettingService.isExist(upc)) {
				MessageBox.show(ItemSettingActivity.this,
						"The upc already exists.", onClickMessageListener,
						MessageDialog.MESSAGE_BOX_OK);
				return;
			}
			itemSetting.setUpc(upc);
			mItemSettingService.save(itemSetting);
			SetItemTareSettingData(tare, upc);
			String errorString = "";
			if (errorString.length() > 0) {
				MessageBox.show(ItemSettingActivity.this, errorString,
						onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
			} else {
				Toast.makeText(ItemSettingActivity.this, "Save completed.",
						Toast.LENGTH_SHORT).show();
				if (price.trim().length() <= 0) {
					price = "0";
				}
				et_upc.setEnabled(false);
				SetEnabledTrue();
				sp_list.setSelection(1);
				et_search.setText(upc);
				Search();
				cb_follow_dept.setEnabled(true);
				if (GlobalInfo.getInstance().isMGNetwork) {
					ItemSetting itemSettingx = mItemSettingService
							.findByUpc(upc);
					mMGCreateFiles.createrFile(itemSettingx.toMGData("INSERT"));
				}
			}
		} else if (SaveMode == "Update") {
			mItemSettingService.save(itemSetting);
			SetItemTareSettingData(tare, upc);
			GetItemDetail(upc);
			Refresh();
			listAdapter.notifyDataSetChanged();
			SetEnabledTrue();
			Toast.makeText(ItemSettingActivity.this, "Save completed.",
					Toast.LENGTH_SHORT).show();
			if (GlobalInfo.getInstance().isMGNetwork) {
				ItemSetting itemSettingx = mItemSettingService.findByUpc(upc);
				mMGCreateFiles.createrFile(itemSettingx.toMGData("UPDATE"));
			}
		}
		SaveMode = "";
		et_search.setText("");
		et_price.setTag(0);
		et_price_2.setTag(0);
		SetPage();
	}

	public void SetItemTareSettingData(int tare, String upc) {
		switch (tare) {
		case 0:
			if (SaveMode == "Update") {
				List<ItemTareSetting> mItemTareSetting = mItemTareService
						.FindTateByUPC(upc);
				if (GlobalInfo.getInstance().isMGNetwork) {
					if (mItemTareSetting != null && mItemTareSetting.size() > 0) {
//						for (int i = 0; i < mItemTareSetting.size(); i++) {
							mMGCreateFiles.createrFile(mItemTareSetting.get(0)
									.toMGData("DELETE"));
//						}
					}
				}
//				for (int i = 0; i < mItemTareSetting.size(); i++) {
					mItemSettingService.DeleteItemTareSetting(upc);
//				}
			}
			break;
		case 1:
			if (SaveMode == "Update") {
				List<ItemTareSetting> mItemTareSetting = mItemTareService
						.FindTateByUPC(upc);
				if (GlobalInfo.getInstance().isMGNetwork) {
					if (mItemTareSetting != null && mItemTareSetting.size() > 0) {
//						for (int i = 0; i < mItemTareSetting.size(); i++) {
							mMGCreateFiles.createrFile(mItemTareSetting.get(0)
									.toMGData("DELETE"));
//						}
					}
				}
//				for (int i = 0; i < mItemTareSetting.size(); i++) {
					mItemSettingService.DeleteItemTareSetting(upc);
//				}
			}
			String tareString = String.valueOf(btn_single_tare.getText());
			int tareId = 0;
			for (int i = 0; i < tareSettingList.size(); i++) {
				if (tareString.equals(tareSettingList.get(i).getTa_desc())) {
					tareId = tareSettingList.get(i).getTa_no();
				}
			}
			mItemSettingService.InsertItemTareSetting(upc, tareId);
			if (GlobalInfo.getInstance().isMGNetwork) {
				List<ItemTareSetting> mItemTareSetting = mItemTareService
						.FindTateByUPC(upc);
				for (int j = 0; j < mItemTareSetting.size(); j++) {
					if (mItemTareSetting != null && mItemTareSetting.size() > 0) {
						mMGCreateFiles.createrFile(mItemTareSetting.get(j)
								.toMGData("INSERT"));
					}
				}
			}
			break;
		case 2:
			if (SaveMode == "Update") {
				List<ItemTareSetting> mItemTareSetting = mItemTareService
						.FindTateByUPC(upc);
				if (GlobalInfo.getInstance().isMGNetwork) {
					if (mItemTareSetting != null && mItemTareSetting.size() > 0) {
//						for (int i = 0; i < mItemTareSetting.size(); i++) {
							mMGCreateFiles.createrFile(mItemTareSetting.get(0)
									.toMGData("DELETE"));
//						}
					}
				}
//				for (int i = 0; i < mItemTareSetting.size(); i++) {
					mItemSettingService.DeleteItemTareSetting(upc);
//				}
			}
			for (int i = 0; i < itemTareList.size(); i++) {
				mItemSettingService.InsertItemTareSetting(upc, itemTareList
						.get(i).getIt_tare_no());
			}

			if (GlobalInfo.getInstance().isMGNetwork) {
				List<ItemTareSetting> mItemTareSetting = mItemTareService
						.FindTateByUPC(upc);
				for (int j = 0; j < mItemTareSetting.size(); j++) {
					if (mItemTareSetting != null && mItemTareSetting.size() > 0) {
						mMGCreateFiles.createrFile(mItemTareSetting.get(j)
								.toMGData("INSERT"));
					}
				}
			}
			break;
		default:
			break;
		}
	}

	public void Refresh() {
		String pagetext = (String) tv_page.getText();
		if (pagetext == null || pagetext.trim().equals("")) {
			pagetext = "1";
		}
		int page = Integer.valueOf(pagetext);
		BindingData((page - 1), searchType, searchString);
		SetPage();
	}

	public void Delete() {
		String upc = String.valueOf(listitem
				.get(listAdapter.GetSelectedIndex()).getUpc());
		List<ItemTareSetting> mItemTareSetting = mItemTareService
				.FindTateByUPC(upc);
		if (GlobalInfo.getInstance().isMGNetwork) {
			ItemSetting itemSetting = mItemSettingService.findByUpc(upc);
			if (itemSetting != null) {
				mMGCreateFiles.createrFile(itemSetting.toMGData("DELETE"));
			}

			MixMatch mMixMatch = mMixMatchService.FindMmByUPC(upc);
			if (mMixMatch != null) {
				mMGCreateFiles.createrFile(mMixMatch.toMGData("DELETE"));
			}

			FlipChart mFlipChart = mFlipChartService.FindFlipChartByUPC(upc);
			if (mFlipChart != null) {
				mMGCreateFiles.createrFile(mFlipChart.toMGData("DELETE"));
			}

			PriceSetting mPriceSetting = mPriceService.getitempricesetting(upc);
			if (mPriceSetting != null) {
				mMGCreateFiles.createrFile(mPriceSetting.toMGData("DELETE"));
			}

			
			if (GlobalInfo.getInstance().isMGNetwork) {
				if (mItemTareSetting != null && mItemTareSetting.size() > 0) {
					for (int i = 0; i < mItemTareSetting.size(); i++) {
						mMGCreateFiles.createrFile(mItemTareSetting.get(i)
								.toMGData("DELETE"));
					}
				}
			}
		}
		mItemSettingService.Delete(upc);
		mItemPicService.ImageDelete(upc);
		mMixMatchService.DeleteMm(upc);
		// delete flipchart and update order
		int order = mItemSettingService.GetFlipChartOrderNo(upc);
		int group = mItemSettingService.GetFlipChartGroup(upc);
		mItemSettingService.postDeleteSetOrder(order, group);
		// //////////////////////////////////
		mFlipChartService.deleteFCByUpc(upc);
		mPriceService.DeletePriceSetting(upc);
		
		for (int i = 0; i < mItemTareSetting.size(); i++) {
			mItemSettingService.DeleteItemTareSetting(upc);
		}

		String pagetext = (String) tv_page.getText();
		if (pagetext == null || pagetext.trim().equals("")) {
			pagetext = "1";
		}

		int page = Integer.valueOf(pagetext);
		BindingData((page - 1), searchType, searchString);
	}

	public void Search() {
		searchString = et_search.getText().toString();
		switch ((int) sp_list.getSelectedItemId()) {
		case SP.ALL:
			searchType = SP.ALL;
			PageCountSize = mItemSettingService.GetPageCountSize(searchType,
					searchString);
			BindingData(0, searchType, searchString);
			SetPage();
			ControlEmpty();
			break;
		case SP.UPC:
			if (searchString != null && !searchString.trim().equals("")) {
				searchType = SP.UPC;
				if (searchString.length() < 14) {
					UPC upc = new UPC(searchString, UPC.INPUT_BY_MANUAL,
							GlobalInfo.getInstance().isNormalize);
					searchString = upc.code;
				}
				PageCountSize = mItemSettingService.GetPageCountSize(
						searchType, searchString);
				BindingData(0, searchType, searchString);
				ControlEmpty();
				SetPage();
			} else {
				et_search.setText("");
				return;
			}
			break;
		case SP.Department:
			if (searchString != null && !searchString.trim().equals("")) {
				searchType = SP.Department;
				if (isNumeric(searchString)) {
					PageCountSize = mItemSettingService.GetPageCountSize(
							searchType, searchString);
					BindingData(0, searchType, searchString);
					SetPage();
				} else {
					if (listitem != null) {
						listitem.clear();
					}
				}
				ControlEmpty();
			} else {
				et_search.setText("");
				return;
			}
			break;
		case SP.SubDept:
			if (searchString != null && !searchString.trim().equals("")) {
				searchType = SP.SubDept;
				if (isNumeric(searchString)) {
					PageCountSize = mItemSettingService.GetPageCountSize(
							searchType, searchString);
					BindingData(0, searchType, searchString);
					SetPage();
				} else {
					if (listitem != null) {
						listitem.clear();
					}
				}
				ControlEmpty();
			} else {
				et_search.setText("");
				return;
			}
			break;
		case SP.Vendor:
			if (searchString != null && !searchString.trim().equals("")) {
				searchType = SP.Vendor;

				PageCountSize = mItemSettingService.GetPageCountSize(
						searchType, searchString);
				BindingData(0, searchType, searchString);
				SetPage();
				ControlEmpty();
			} else {
				et_search.setText("");
				return;
			}
			break;
		}
		RefresItem();
	}

	public void RefresItem() {
		if (listitem != null) {
			if (listitem.size() > 0) {
				listAdapter.ScrollToRow(0);
				String upc = String.valueOf(listitem.get(0).getUpc());
				ChangeMode.mode = 0;
				GetItemDetail(upc);
				cb_follow_dept.setEnabled(true);
				cb_coupon.setEnabled(true);
				InitializeEnabledTrue();
				SetCouponStatus(cb_coupon.isChecked());
				ChangeMode.mode = 1;
			} else {
				tv_page.setText(String.valueOf(""));
				listAdapter.ScrollToRow(-1);
				btn_back.setVisibility(View.INVISIBLE);
				btn_next.setVisibility(View.INVISIBLE);
				MessageBox.show(ItemSettingActivity.this, "Item Not Found.",
						onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
				InitializeEnabledFalse();
				et_search.requestFocus();
			}
		} else {
			InitializeEnabledFalse();
		}
		et_search.setText("");
	}

	public void BindingData(int page, int SPType, String searchString) {
		if (listitem == null) {
			listitem = new ArrayList<ItemSetting>();
			listitem = mItemSettingService.SearchItems(page, SPType,
					searchString);
			listAdapter = new ListAdapter(this, listitem);
			list.setAdapter(listAdapter);
			list.setOnItemClickListener(onItemClickListener);
		} else {
//			listitem.clear();
			listitem = mItemSettingService.SearchItems(page, SPType,
					searchString);
			listAdapter.setSource(listitem);
			listAdapter.notifyDataSetChanged();
		}
	}

	public void Keyboard() {
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(ItemSettingActivity.this
				.getCurrentFocus().getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}

	private TextWatcher watcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable s) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			if (ChangeMode.mode == 1) {
				SetEnabledFalse();
				if (SaveMode != "Insert") {
					SaveMode = "Update";
					if (et_price.isFocused()) {
						et_price.setTag(1);
					}
					if (et_price_2.isFocused()) {
						et_price_2.setTag(1);
					}
				}
			}
		}
	};
	


	public void SetEnabledFalse() {
		btn_add.setEnabled(false);
		btn_del.setEnabled(false);
		btn_exit.setEnabled(false);
		btn_search.setEnabled(false);
		btn_import.setEnabled(false);
		list.setEnabled(false);
		btn_undo.setEnabled(true);
		btn_save.setEnabled(true);
		btn_next.setVisibility(View.INVISIBLE);
		btn_back.setVisibility(View.INVISIBLE);
		iv_price_setting.setEnabled(false);
	}

	public void SetEnabledTrue() {
		btn_add.setEnabled(true);
		btn_del.setEnabled(true);
		btn_exit.setEnabled(true);
		btn_search.setEnabled(true);
		btn_import.setEnabled(true);
		list.setEnabled(true);
		btn_undo.setEnabled(false);
		btn_save.setEnabled(false);
		if (cb_coupon.isChecked() == false) {
			iv_price_setting.setEnabled(true);
		} else {
			cb_age_ver.setEnabled(false);
			cb_scale_weight.setEnabled(false);
		}
	}

	public void SetPage() {
		String pagetext = (String) tv_page.getText();
		if (pagetext == null || pagetext.trim().equals("")) {
			pagetext = "1";
		}
		int page = Integer.valueOf(pagetext);
		if (PageCountSize > page) {
			btn_next.setVisibility(View.VISIBLE);
		} else {
			btn_next.setVisibility(View.INVISIBLE);
		}
		if (PageCountSize > 1 && page > 1) {
			btn_back.setVisibility(View.VISIBLE);
		} else {
			btn_back.setVisibility(View.INVISIBLE);
		}
	}

	ImageView iv_image = null;
	ImageView iv_clean_img = null;
	Dialog dialog = null;

	private void ImageWindow() {
		if (dialog == null) {
			dialog = new Dialog(this, R.style.dialog2);
			dialog.setContentView(R.layout.dialog_perview_pic);
		}
		Button btn_browse = (Button) dialog.findViewById(R.id.btn_browse);
		Button btn_ok = (Button) dialog.findViewById(R.id.btn_ok);
		Button btn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
		btn_browse.setOnClickListener(onClickPopupWindowListener);
		btn_ok.setOnClickListener(onClickPopupWindowListener);
		btn_cancel.setOnClickListener(onClickPopupWindowListener);
		iv_image = (ImageView) dialog.findViewById(R.id.iv_image);
		iv_clean_img = (ImageView) dialog.findViewById(R.id.iv_clean_img);
		iv_clean_img.setOnClickListener(onClickPopupWindowListener);
		int index = listAdapter.GetSelectedIndex();
		String upc = String.valueOf(listitem.get(index).getUpc());
		Bitmap bp = mItemPicService.getImageByUPC(upc);
		if (bp == null) {
			Bitmap logo = BitmapFactory.decodeResource(ItemSettingActivity.this
					.getApplicationContext().getResources(),
					R.drawable.moleqlogo);
			iv_image.setImageBitmap(logo);
			iv_clean_img.setVisibility(View.GONE);
		} else {
			iv_image.setImageBitmap(bp);
			iv_clean_img.setVisibility(View.VISIBLE);
		}
		dialog.show();
	}

	Dialog netWtDialog = null;

	private void NetWTWindow() {
		if (netWtDialog == null) {
			netWtDialog = new Dialog(this, R.style.dialog2);
			netWtDialog.setContentView(R.layout.dialog_perview_net_wt);
		}
		ListView lv_net_wt_list = (ListView) netWtDialog
				.findViewById(R.id.lv_net_wt_list);
		Button btn_net_wt_ok = (Button) netWtDialog
				.findViewById(R.id.btn_net_wt_ok);
		Button btn_net_wt_cancel = (Button) netWtDialog
				.findViewById(R.id.btn_net_wt_cancel);
		Button btn_net_wt_search = (Button) netWtDialog
				.findViewById(R.id.btn_net_wt_search);
		if (netWTAdapter == null) {
			netWTAdapter = new NetWTAdapter(this, NetWTList);
			lv_net_wt_list.setAdapter(netWTAdapter);
		}
		int position = GetNetWTPosition(String.valueOf(btn_net_wt.getText()));
		netWTAdapter.setSource(NetWTList);
		netWTAdapter.notifyDataSetChanged();
		netWTAdapter.ScrollToRow(position);
		lv_net_wt_list.setSelection(position);
		btn_net_wt_ok.setOnClickListener(onClickPopupWindowListener);
		btn_net_wt_cancel.setOnClickListener(onClickPopupWindowListener);
		btn_net_wt_search.setOnClickListener(onClickPopupWindowListener);
		lv_net_wt_list.setOnItemClickListener(onItemClickListener);
		netWtDialog.show();
	}

	Dialog deptDialog = null;

	private void DeptWindow() {
		if (deptDialog == null) {
			deptDialog = new Dialog(this, R.style.dialog2);
			deptDialog.setContentView(R.layout.dialog_perview_dept);
		}
		ListView lv_dept_list = (ListView) deptDialog
				.findViewById(R.id.lv_dept_list);
		Button btn_dept_ok = (Button) deptDialog.findViewById(R.id.btn_dept_ok);
		Button btn_dept_cancel = (Button) deptDialog
				.findViewById(R.id.btn_dept_cancel);
			
		deptAdapter = new SelectionAdapter(this, AdapterDataSourceBuilder.readValueFromSubDep(DeptList));
		lv_dept_list.setAdapter(deptAdapter);
			
		int position = GetDeptPosition(String.valueOf(btn_dep.getText()));
		deptAdapter.ScrollToRow(position);
		lv_dept_list.setOnItemClickListener(onItemClickListener);
		btn_dept_ok.setOnClickListener(onClickPopupWindowListener);
		btn_dept_cancel.setOnClickListener(onClickPopupWindowListener);
		deptDialog.show();
	}

	Dialog tareDialog = null;

	private void TareChooseWindow() {
		if (tareDialog == null) {
			tareDialog = new Dialog(this, R.style.dialog2);
			tareDialog.setContentView(R.layout.dialog_perview_tare);
		}
		ListView lv_tare_list = (ListView) tareDialog
				.findViewById(R.id.lv_tare_list);
		Button btn_tare_ok = (Button) tareDialog.findViewById(R.id.btn_tare_ok);
		Button btn_tare_cancel = (Button) tareDialog
				.findViewById(R.id.btn_tare_cancel);
		
		 tareItems = new ArrayList<String>();
		tareItems.add("No");
		tareItems.add("Single");
		tareItems.add("Multiple");
		
	
		tareChooseAdapter = new SelectionAdapter(this, tareItems);
		lv_tare_list.setAdapter(tareChooseAdapter);
		
		int position = GetTarePosition(String.valueOf(btn_tare.getText()));
		tareChooseAdapter.ScrollToRow(position);
		lv_tare_list.setOnItemClickListener(onItemClickListener);
		btn_tare_ok.setOnClickListener(onClickPopupWindowListener);
		btn_tare_cancel.setOnClickListener(onClickPopupWindowListener);
		tareDialog.show();
	}

	Dialog tareSettingDialog = null;

	private void TareSettingWindow() {
		if (tareSettingDialog == null) {
			tareSettingDialog = new Dialog(this, R.style.dialog2);
			tareSettingDialog
					.setContentView(R.layout.dialog_perview_tare_setting);
		}
		ListView lv_tare_list = (ListView) tareSettingDialog
				.findViewById(R.id.lv_tare_setting_list);
		Button btn_tare_ok = (Button) tareSettingDialog
				.findViewById(R.id.btn_tare_setting_ok);
		Button btn_tare_cancel = (Button) tareSettingDialog
				.findViewById(R.id.btn_tare_setting_cancel);
		if (tareSettingAdapter == null) {
			tareSettingAdapter = new TareSelectionAdapter(this, tareSettingList);
			lv_tare_list.setAdapter(tareSettingAdapter);
		}
		if (String.valueOf(btn_single_tare.getText()).length() > 0) {
			int position = GetItemTarePosition(String.valueOf(btn_single_tare
					.getText()));
			tareSettingAdapter.ScrollToRow(position);
		}
		tareSettingAdapter.ScrollToRow(0);
		lv_tare_list.setOnItemClickListener(onItemClickListener);
		btn_tare_ok.setOnClickListener(onClickPopupWindowListener);
		btn_tare_cancel.setOnClickListener(onClickPopupWindowListener);
		tareSettingDialog.show();
	}

	Dialog bottleDialog = null;

	private void BottleWindow() {
		if (bottleDialog == null) {
			bottleDialog = new Dialog(this, R.style.dialog2);
			bottleDialog.setContentView(R.layout.dialog_perview_bottle_deposit);
		}
		ListView lv_bottle_deposit_list = (ListView) bottleDialog
				.findViewById(R.id.lv_bottle_deposit_list);
		Button btn_bottle_deposit_ok = (Button) bottleDialog
				.findViewById(R.id.btn_bottle_deposit_ok);
		Button btn_bottle_deposit_cancel = (Button) bottleDialog
				.findViewById(R.id.btn_bottle_deposit_cancel);
		if (bottleAdapter == null) {
			bottleAdapter = new BottleAdapter(this, bottleList);
			lv_bottle_deposit_list.setAdapter(bottleAdapter);
			bottleAdapter.ScrollToRow(0);
		}
		if (String.valueOf(btn_bottle_deposit.getText()).equals("")) {
			bottleAdapter.ScrollToRow(0);
		} else {
			int position = GetBottlePosition(String.valueOf(btn_bottle_deposit
					.getText()));
			bottleAdapter.ScrollToRow(position);
		}
		lv_bottle_deposit_list.setOnItemClickListener(onItemClickListener);
		btn_bottle_deposit_ok.setOnClickListener(onClickPopupWindowListener);
		btn_bottle_deposit_cancel
				.setOnClickListener(onClickPopupWindowListener);
		bottleDialog.show();
	}

//	Dialog ageDialog = null;
//	EditText et_age_name, et_age_value;
//	ImageView iv_age_dialog_add, iv_age_dialog_delete, iv_age_dialog_update,
//			iv_age_dialog_complete;
//	Button btn_age_dialog_ok, btn_age_dialog_cancel;
//	ListView lv_age_dialog_list;
//
//	private void ageWindow() {
//		if (ageDialog == null) {
//			ageDialog = new Dialog(this, R.style.dialog2);
//			ageDialog.setContentView(R.layout.dept_age_dialog_perview_models);
//		}
//		lv_age_dialog_list = (ListView) ageDialog
//				.findViewById(R.id.lv_age_dialog_list);
//		btn_age_dialog_ok = (Button) ageDialog
//				.findViewById(R.id.btn_age_dialog_ok);
//		btn_age_dialog_cancel = (Button) ageDialog
//				.findViewById(R.id.btn_age_dialog_cancel);
//		iv_age_dialog_add = (ImageView) ageDialog
//				.findViewById(R.id.iv_age_dialog_add);
//		iv_age_dialog_complete = (ImageView) ageDialog
//				.findViewById(R.id.iv_age_dialog_ok);
//		iv_age_dialog_delete = (ImageView) ageDialog
//				.findViewById(R.id.iv_age_dialog_delete);
//		iv_age_dialog_update = (ImageView) ageDialog
//				.findViewById(R.id.iv_age_dialog_update);
//		et_age_name = (EditText) ageDialog.findViewById(R.id.et_age_name);
//		et_age_value = (EditText) ageDialog.findViewById(R.id.et_age_value);
//		if (ageAdapter == null) {
//			ageAdapter = new AgeAdapter(this, ageList);
//			lv_age_dialog_list.setAdapter(ageAdapter);
//			ageAdapter.ScrollToRow(0);
//		}
//		ageList = mAgeSettingService.FindAll();
//		ageAdapter.setSource(ageList);
//		ageAdapter.notifyDataSetChanged();
//		if (String.valueOf(btn_age_ver.getText()).equals("")) {
//			ageAdapter.ScrollToRow(0);
//		} else {
//			int position = GetAgePosition(String.valueOf(btn_age_ver.getText()));
//			ageAdapter.ScrollToRow(position);
//		}
//		lv_age_dialog_list.setOnItemClickListener(onItemClickListener);
//		btn_age_dialog_ok.setOnClickListener(onClickPopupWindowListener);
//		btn_age_dialog_cancel.setOnClickListener(onClickPopupWindowListener);
//		iv_age_dialog_add.setOnClickListener(onClickPopupWindowListener);
//		iv_age_dialog_complete.setOnClickListener(onClickPopupWindowListener);
//		iv_age_dialog_delete.setOnClickListener(onClickPopupWindowListener);
//		iv_age_dialog_update.setOnClickListener(onClickPopupWindowListener);
//		ageDialog.show();
//	}
	Dialog printerDialog = null;
	
	private void PrinterWindow() {
		if (printerDialog == null) {
			printerDialog = new Dialog(this, R.style.dialog2);
			printerDialog.setContentView(R.layout.dialog_perview_choose_printer);
		}
		ListView lv_printer_list = (ListView) printerDialog
				.findViewById(R.id.lv_printer_list);
		Button btn_printer_ok = (Button) printerDialog
				.findViewById(R.id.btn_printer_ok);
		Button btn_printer_cancel = (Button) printerDialog
				.findViewById(R.id.btn_printer_cancel);
		if (printerAdapter == null) {
			printerAdapter = new PrinterAdapter(this, printerList);
			lv_printer_list.setAdapter(printerAdapter);
			printerAdapter.ScrollToRow(0);
		}
		if (String.valueOf(btn_printer.getText()).equals("")) {
			printerAdapter.ScrollToRow(0);
		} else {
			int position = GetPrinterPosition(String.valueOf(btn_printer
					.getText()));
			printerAdapter.ScrollToRow(position);
		}
		lv_printer_list.setOnItemClickListener(onItemClickListener);
		btn_printer_ok.setOnClickListener(onClickPopupWindowListener);
		btn_printer_cancel
				.setOnClickListener(onClickPopupWindowListener);
		printerDialog.show();
	}

	Dialog priceDialog = null;
	EditText et_cp_amt, et_cp_price, et_np_amt, et_np_price, et_st_date,
			et_st_time, et_et_date, et_et_time, et_pp_amt, et_pp_price,
			et_lq_amt, et_lq_price, et_da_price, et_percent_amt;
	Button btn_price_setting_save, btn_price_setting_back, btn_mm,
			btn_dis_link;
	ImageButton ibtn_clear_date, ibtn_clear_mm, ibtn_clear_dis_link;

	private void PriceSettingWindow(String upc) {
		if (priceDialog == null) {
			priceDialog = new Dialog(this, R.style.dialog2);
			priceDialog.setContentView(R.layout.dialog_perview_price);
			Window win = priceDialog.getWindow();
			WindowManager.LayoutParams lp = win.getAttributes();
			lp.y = -50;
		}
		mDisLinkItemDiscountDialog = new ItemDiscountDialog(
				ItemSettingActivity.this, ItemSettingActivity.this);
		et_cp_amt = (EditText) priceDialog.findViewById(R.id.et_cp_amt);
		et_cp_price = (EditText) priceDialog.findViewById(R.id.et_cp_price);
		et_np_amt = (EditText) priceDialog.findViewById(R.id.et_np_amt);
		et_np_price = (EditText) priceDialog.findViewById(R.id.et_np_price);
		et_st_date = (EditText) priceDialog.findViewById(R.id.et_st_date);
		et_st_time = (EditText) priceDialog.findViewById(R.id.et_st_time);
		et_et_date = (EditText) priceDialog.findViewById(R.id.et_et_date);
		et_et_time = (EditText) priceDialog.findViewById(R.id.et_et_time);
		et_pp_amt = (EditText) priceDialog.findViewById(R.id.et_pp_amt);
		et_pp_price = (EditText) priceDialog.findViewById(R.id.et_pp_price);
		et_lq_amt = (EditText) priceDialog.findViewById(R.id.et_lq_amt);
		et_lq_price = (EditText) priceDialog.findViewById(R.id.et_lq_price);
		et_da_price = (EditText) priceDialog.findViewById(R.id.et_da_price);
		et_percent_amt = (EditText) priceDialog
				.findViewById(R.id.et_percent_amt);
		btn_mm = (Button) priceDialog.findViewById(R.id.btn_mm);
		ibtn_clear_date = (ImageButton) priceDialog
				.findViewById(R.id.ibtn_clear_date);
		ibtn_clear_mm = (ImageButton) priceDialog
				.findViewById(R.id.ibtn_clear_mm);
		btn_price_setting_save = (Button) priceDialog
				.findViewById(R.id.btn_price_setting_save);
		btn_price_setting_back = (Button) priceDialog
				.findViewById(R.id.btn_price_setting_back);
		al_price_detail = (AbsoluteLayout) priceDialog
				.findViewById(R.id.ll_price_detail);
		btn_dis_link = (Button) priceDialog.findViewById(R.id.btn_dis_link);
		ibtn_clear_dis_link = (ImageButton) priceDialog
				.findViewById(R.id.ibtn_clear_dis_link);
		et_cp_amt.addTextChangedListener(itemwatcher);
		et_cp_price.addTextChangedListener(itemwatcher);
		et_da_price.addTextChangedListener(watcher2);
		et_et_date.addTextChangedListener(watcher2);
		et_et_time.addTextChangedListener(watcher2);
		et_lq_amt.addTextChangedListener(watcher2);
		et_lq_price.addTextChangedListener(watcher2);
		et_np_amt.addTextChangedListener(watcher2);
		et_np_price.addTextChangedListener(watcher2);
		et_percent_amt.addTextChangedListener(watcher2);
		et_pp_amt.addTextChangedListener(watcher2);
		et_pp_price.addTextChangedListener(watcher2);
		btn_mm.addTextChangedListener(watcher2);
		et_st_date.addTextChangedListener(watcher2);
		et_st_time.addTextChangedListener(watcher2);
		btn_dis_link.addTextChangedListener(watcher2);
		ibtn_clear_date.setOnClickListener(onClickListener);
		ibtn_clear_mm.setOnClickListener(onClickListener);
		btn_mm.setOnClickListener(onClickListener);
		btn_dis_link.setOnClickListener(onClickListener);
		ibtn_clear_dis_link.setOnClickListener(onClickListener);
		al_price_detail.setOnClickListener(onClickListener);
		et_st_date.setOnClickListener(onTextClickListener);
		et_st_time.setOnClickListener(onTextClickListener);
		et_et_date.setOnClickListener(onTextClickListener);
		et_et_time.setOnClickListener(onTextClickListener);
		btn_price_setting_save.setOnClickListener(onClickPopupWindowListener);
		btn_price_setting_back.setOnClickListener(onClickPopupWindowListener);
		RefresItemPrice(upc);
		SetPriceEnabledTrue();
		priceDialog.show();
	}

	Dialog importDialog = null;
	Button btn_go, btn_close, btn_browse, btn_type;
	TextView tv_percentage;
	EditText et_path;
	ProgressBar pb_loading;
	List<String[]> csvList = null;
	int TotalCount = 0;

	private void ImportItemWindow() {
		if (importDialog == null) {
			importDialog = new Dialog(this, R.style.dialog2);
			importDialog.setContentView(R.layout.dialog_perview_import_item);
		}
		btn_go = (Button) importDialog.findViewById(R.id.btn_go);
		btn_close = (Button) importDialog.findViewById(R.id.btn_close);
		btn_browse = (Button) importDialog.findViewById(R.id.btn_browse);
		et_path = (EditText) importDialog.findViewById(R.id.et_path);
		btn_type = (Button) importDialog.findViewById(R.id.btn_type);
		tv_percentage = (TextView) importDialog
				.findViewById(R.id.tv_percentage);
		pb_loading = (ProgressBar) importDialog.findViewById(R.id.pb_loading);
		btn_go.setOnClickListener(ImportItemOnClickListener);
		btn_close.setOnClickListener(ImportItemOnClickListener);
		btn_browse.setOnClickListener(ImportItemOnClickListener);
		btn_type.setOnClickListener(ImportItemOnClickListener);
		et_path.setText("");
		btn_type.setText("Insert/Update");
		importDialog.show();
	}

	public OnClickListener ImportItemOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.btn_go:
				String path = et_path.getText().toString();
				if (path.trim().equals("")) {
					MessageBox.show(ItemSettingActivity.this,
							"Please select the path.", onClickMessageListener,
							MessageDialog.MESSAGE_BOX_OK);
					return;
				}
				isImport = true;
				MessageBox.show(ItemSettingActivity.this,
						"Do you want to import now?", onClickMessageListener,
						MessageDialog.MESSAGE_BOX_YES_NO);
				break;
			case R.id.btn_close:
				pb_loading.setProgress(0);
				tv_percentage.setText("");
				importDialog.dismiss();
				break;
			case R.id.btn_browse:
				pb_loading.setProgress(0);
				tv_percentage.setText("");
				Intent intent = new Intent();
				intent.putExtra("filePath", filePathString);
				intent.setClass(ItemSettingActivity.this,
						ImportDataFilePickerActivity.class);
				ItemSettingActivity.this.startActivityForResult(intent,
						CONTEXT_RESTRICTED);
				is_import_data = true;
				break;
			case R.id.btn_type:
				pb_loading.setProgress(0);
				tv_percentage.setText("");
				ImportTypeWindow();
				break;
			default:
				break;
			}
		}
	};

	public String changeCharset(String str, String oldCharset, String newCharset){
		if (str != null) {
			byte[] bs;
			try {
				bs = str.getBytes(oldCharset);
				return new String(bs, newCharset);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} else {
			return null;
		}
		return null;
	}

	public String changeCharset(String str, String newCharset) {
		try {
			if (str != null) {
				byte[] bs = str.getBytes();
				return new String(bs, newCharset);
			} else {
				return null;
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public void ImportData() {
		String path = et_path.getText().toString();
		csvList = ReadFileTools.readeCsv(path);
		int count = csvList.size();
		if (count <= 0)
			return;
		pb_loading.setMax(count);
		pb_loading.setProgress(0);
		tv_percentage.setText("");
		TotalCount = 0;
		final String type = btn_type.getText().toString();
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < csvList.size(); i++) {
					pb_loading.incrementProgressBy(1);
					String barcode = csvList.get(i)[0];
					UPC upc = new UPC(barcode, UPC.INPUT_BY_MANUAL, GlobalInfo
							.getInstance().isNormalize);
					barcode = upc.code;
					boolean result = mItemSettingService
							.CheckItemSetting(barcode);
					ImportData importData;
					importData = new ImportData(barcode, changeCharset(csvList.get(i)[1], "UTF-8"),
							changeCharset(csvList.get(i)[2], "UTF-8"), csvList
									.get(i)[3], csvList.get(i)[4], csvList
									.get(i)[5], csvList.get(i)[6], csvList
									.get(i)[7], csvList.get(i)[8], csvList
									.get(i)[9], csvList.get(i)[10], csvList
									.get(i)[11], csvList.get(i)[12], csvList
									.get(i)[13], csvList.get(i)[14], csvList
									.get(i)[15], csvList.get(i)[16], csvList
									.get(i)[17], csvList.get(i)[18], csvList
									.get(i)[19], csvList.get(i)[20]);

					if (type.equals("Insert")) {
						if (!result) {
							mItemSettingService.ImportAddData(importData);
							TotalCount++;
						}
					} else if (type.equals("Update")) {
						if (result) {
							mItemSettingService.ImportUpdataData(importData);
							TotalCount++;
						}
					} else if (type.equals("Insert/Update")) {
						if (result) {
							mItemSettingService.ImportUpdataData(importData);
							TotalCount++;
						} else {
							mItemSettingService.ImportAddData(importData);
							TotalCount++;
						}
					}
					Message message = new Message();
					message.what = ItemSettingActivity.GUI_THREADING_NOTIFIER;
					MessageHandler.sendMessage(message);
				}
				Message message = new Message();
				message.what = ItemSettingActivity.GUI_STOP_NOTIFIER;
				MessageHandler.sendMessage(message);
				isImport = false;
			}
		}).start();
	}

	Handler MessageHandler = new Handler() {
		public void handleMessage(Message message) {
			switch (message.what) {
			case ItemSettingActivity.GUI_STOP_NOTIFIER:
				Toast.makeText(
						ItemSettingActivity.this,
						String.valueOf(TotalCount)
								+ " Item(s) have been processed.",
						Toast.LENGTH_LONG).show();
				Thread.currentThread().interrupt();
				break;
			case ItemSettingActivity.GUI_THREADING_NOTIFIER:
				if (!Thread.currentThread().isInterrupted()) {
					double a = pb_loading.getProgress();
					double b = csvList.size();
					double i = a / b * 100;
					pb_loading.setVisibility(View.VISIBLE);
					tv_percentage.setText((int) i + "%");
				}
				break;
			}
		}
	};
	Dialog importTypeDialog = null;
	Button btn_import_type_ok, btn_import_type_cancel;
	ListView lv_import_type_list;
	ImportTypeAdapter importTypeAdapter = null;

	private void ImportTypeWindow() {
		if (importTypeDialog == null) {
			importTypeDialog = new Dialog(this, R.style.dialog2);
			importTypeDialog
					.setContentView(R.layout.dialog_perview_import_type);
		}
		btn_import_type_ok = (Button) importTypeDialog
				.findViewById(R.id.btn_import_type_ok);
		btn_import_type_cancel = (Button) importTypeDialog
				.findViewById(R.id.btn_import_type_cancel);
		lv_import_type_list = (ListView) importTypeDialog
				.findViewById(R.id.lv_import_type_list);
		String[] itemSource = new String[] { "Insert/Update", "Insert",
				"Update" };
		if (importTypeAdapter == null) {
			importTypeAdapter = new ImportTypeAdapter(this, itemSource);
		}
		lv_import_type_list.setAdapter(importTypeAdapter);
		btn_import_type_ok.setOnClickListener(ImportTypeOnClickListener);
		btn_import_type_cancel.setOnClickListener(ImportTypeOnClickListener);
		lv_import_type_list.setOnItemClickListener(onItemClickListener);
		String type = btn_type.getText().toString();
		if (type.equals("Insert/Update")) {
			importTypeAdapter.ScrollToRow(0);
		} else if (type.equals("Insert")) {
			importTypeAdapter.ScrollToRow(1);
		} else if (type.equals("Update")) {
			importTypeAdapter.ScrollToRow(2);
		}
		importTypeDialog.show();
	}

	public OnClickListener ImportTypeOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.btn_import_type_ok:
				int position = importTypeAdapter.GetSelectedIndex();
				if (position >= 0) {
					btn_type.setText(importTypeAdapter.getItem(position)
							.toString());
				}
				importTypeDialog.dismiss();
				break;
			case R.id.btn_import_type_cancel:
				importTypeDialog.dismiss();
				break;
			default:
				break;
			}
		}
	};

	public int validation() {
		String da_price, et_date, et_time, lq_amt, lq_price, np_amt, np_price, percent_amt, pp_amt, pp_price, st_date, st_time, pmm, cp_price, cp_amt;
		cp_price = et_cp_price.getText().toString();
		cp_amt = et_cp_amt.getText().toString();
		da_price = et_da_price.getText().toString();
		et_date = et_et_date.getText().toString();
		et_time = et_et_time.getText().toString();
		lq_amt = et_lq_amt.getText().toString();
		lq_price = et_lq_price.getText().toString();
		np_amt = et_np_amt.getText().toString();
		np_price = et_np_price.getText().toString();
		percent_amt = et_percent_amt.getText().toString();
		pp_amt = et_pp_amt.getText().toString();
		pp_price = et_pp_price.getText().toString();
		st_date = et_st_date.getText().toString();
		st_time = et_st_time.getText().toString();
		pmm = btn_mm.getText().toString();
		boolean zeroPrice = false;
		zeroPrice = GlobalInfo.getInstance().isZeroPrice;
		
		if (!cp_amt.equals("") && cp_price.equals("")) {
			MessageBox.show(ItemSettingActivity.this,
					"Current Price can not be empty.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		if (!cp_price.equals("") && isNum(cp_price) == false) {
			MessageBox.show(ItemSettingActivity.this,
					"Please enter a valid Current Price.",
					onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		if (!cp_price.equals("") && Double.valueOf(cp_price) == 0 && !zeroPrice) {
			MessageBox.show(ItemSettingActivity.this,
					"Item Price cannot be zero.",
					onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
			et_cp_price.requestFocus();
			return -1;
		}
		if (!np_amt.equals("") && np_price.equals("")) {
			MessageBox.show(ItemSettingActivity.this,
					"Next Price can not be empty.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		if (!np_price.equals("") && isNum(np_price) == false) {
			MessageBox.show(ItemSettingActivity.this,
					"Please enter a valid Next Price.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		if (!np_price.equals("") && Double.valueOf(np_price) == 0 && !zeroPrice) {
			MessageBox.show(ItemSettingActivity.this,
					"Item Price cannot be zero.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			et_np_price.requestFocus();
			return -1;
		}
		if (!pp_amt.equals("") && pp_price.equals("")) {
			MessageBox.show(ItemSettingActivity.this,
					"Pkg Price can not be empty.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		if (!pp_price.equals("") && isNum(pp_price) == false) {
			MessageBox.show(ItemSettingActivity.this,
					"Please enter a valid Pkg Price.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		if (!pp_price.equals("") && Double.valueOf(pp_price) == 0 && !zeroPrice) {
			MessageBox.show(ItemSettingActivity.this,
					"Item Price cannot be zero.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			et_pp_price.requestFocus();
			return -1;
		}
		
		if (da_price.equals("0")) {
			MessageBox.show(ItemSettingActivity.this,
					"Discount Amount can not be zero.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		
		if (percent_amt.equals("0")) {
			MessageBox.show(ItemSettingActivity.this,
					"Discount Rate can not be zero.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		
		if (lq_amt.equals("0")) {
			MessageBox.show(ItemSettingActivity.this,
					"Limited Qty can not be zero.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		
		if (!lq_price.equals("") && lq_amt.equals("")) {
			MessageBox.show(ItemSettingActivity.this,
					"Limited Qty can not be empty.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		
		
		if (!lq_amt.equals("") && lq_price.equals("")) {
			MessageBox.show(ItemSettingActivity.this,
					"Limited Price can not be empty.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		if (!lq_price.equals("") && isNum(lq_price) == false) {
			MessageBox.show(ItemSettingActivity.this,
					"Please enter a valid Limited Price.",
					onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		if (!lq_price.equals("") && Double.valueOf(lq_price) == 0 && !zeroPrice) {
			MessageBox.show(ItemSettingActivity.this,
					"Item Price cannot be zero.",
					onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
			et_lq_price.requestFocus();
			return -1;
		}
		
		if (!st_date.equals("") && st_time.equals("")) {
			MessageBox.show(ItemSettingActivity.this,
					"Start Time can not be empty.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		if (!st_date.equals("") && st_time.equals("")) {
			MessageBox.show(ItemSettingActivity.this,
					"Start Time can not be empty.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		if (!et_date.equals("") && et_time.equals("")) {
			MessageBox.show(ItemSettingActivity.this,
					"End Time can not be empty.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		if (st_date.equals("") && !st_time.equals("")) {
			MessageBox.show(ItemSettingActivity.this,
					"Start Date can not be empty.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		if (et_date.equals("") && !et_time.equals("")) {
			MessageBox.show(ItemSettingActivity.this,
					"End Date can not be empty.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}
		int sd, ed, st, et;
		sd = st_date.trim().length();
		ed = et_date.trim().length();
		st = st_time.trim().length();
		et = et_time.trim().length();
		if (sd + ed + st + et > 0) {
			if (sd <= 0) {
				MessageBox.show(ItemSettingActivity.this,
						"Start Date can not be empty.", onClickMessageListener,
						MessageDialog.MESSAGE_BOX_OK);
				return -1;
			}

			if (ed <= 0) {
				MessageBox.show(ItemSettingActivity.this,
						"End Date can not be empty.", onClickMessageListener,
						MessageDialog.MESSAGE_BOX_OK);
				return -1;
			}

			if (st <= 0) {
				MessageBox.show(ItemSettingActivity.this,
						"Start Time can not be empty.", onClickMessageListener,
						MessageDialog.MESSAGE_BOX_OK);
				return -1;
			}

			if (et <= 0) {
				MessageBox.show(ItemSettingActivity.this,
						"End Time can not be empty.", onClickMessageListener,
						MessageDialog.MESSAGE_BOX_OK);
				return -1;
			}
		}

		if (!percent_amt.equals("") && Double.valueOf(percent_amt) > 100) {
			MessageBox.show(ItemSettingActivity.this,
					"Cannot be more than 100%.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}

		if (cp_price.equals("")) {
			MessageBox.show(ItemSettingActivity.this,
					"Current Price can not be empty.", onClickMessageListener,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}

		Date curDate_s = null, curDate_e = null;
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		try {
			curDate_s = format1.parse(st_date);
			curDate_e = format1.parse(et_date);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		if (!et_date.equals("") && !st_date.equals("")) {
			if (curDate_e.before(curDate_s)) {
				MessageBox.show(ItemSettingActivity.this,
						"End Date cannot be earilier than Start Date.",
						onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
				return -1;
			}
			if (!st_time.equals("") && !et_time.equals("")) {
				if (et_date.equals(st_date)
						&& gettime_short(et_time) < gettime_short(st_time)) {
					MessageBox.show(ItemSettingActivity.this,
							"End Time cannot be earilier than Start Time.",
							onClickMessageListener,
							MessageDialog.MESSAGE_BOX_OK);
					return -1;
				}
			}
		}
		return 1;
	}

	public int gettime_short(String time) {
		int str;
		if (time == null) {
			str = 0;
		} else {
			str = Integer.valueOf(time.replace(":", ""));
		}
		return str;
	};

	public static boolean isNum(String str) {
		return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
	}

	public void RefresItemPrice(String upc) {
		PriceSetting price = new PriceSetting();
		ItemSetting itemSetting = new ItemSetting();
		price = mPriceService.getitemprice(upc);
		itemSetting = mItemSettingService.findByUpc(upc);
		dis = null;
		et_cp_amt.setText((itemSetting.getMultple() <= 1) ? "" : String
				.valueOf(itemSetting.getMultple()));
		et_cp_price.setText(String.format("%.2f", itemSetting.getPrice()));
		if (price == null) {
			setempty();
		} else {
			et_da_price.setText((price.getDiscountamount() == null) ? ""
					: String.format("%.2f",
							Double.valueOf(price.getDiscountamount())));
			et_et_date.setText(getdatetime(price.getEnddate() == null ? ""
					: String.valueOf(price.getEnddate())));
			et_et_time.setText(gettime(price.getEndtime()));
			et_lq_amt.setText((price.getLimitedqtyamount() == null || Integer
					.valueOf(price.getLimitedqtyamount()) < 1) ? "" : String
					.valueOf(price.getLimitedqtyamount()));
			et_lq_price.setText((price.getLimitedqtyprice() == null) ? ""
					: String.format("%.2f",
							Double.valueOf(price.getLimitedqtyprice())));
			et_np_amt.setText((price.getPriceMultiple() == null || Integer
					.valueOf(price.getPriceMultiple()) <= 1) ? "" : String
					.valueOf(price.getPriceMultiple()));

			et_np_price.setText((price.getPrice() == null) ? "" : String
					.format("%.2f", Double.valueOf(price.getPrice())));
			et_percent_amt
					.setText((price.getDiscountpercent() == null || Double
							.valueOf(price.getDiscountpercent()) < 0) ? ""
							: String.format("%.2f",
									Double.valueOf(price.getDiscountpercent())));
			et_pp_amt
					.setText((price.getPackagepricemultiple() == null || Integer
							.valueOf(price.getPackagepricemultiple()) <= 1) ? ""
							: String.valueOf(price.getPackagepricemultiple()));
			et_pp_price.setText((price.getPackageprice() == null) ? "" : String
					.format("%.2f", Double.valueOf(price.getPackageprice())));
			et_st_date.setText(getdatetime(price.getStartdate()));
			et_st_time.setText(gettime(price.getStarttime()));
			btn_mm.setText((price.getPricemm() == null) ? "" : String
					.valueOf(price.getPricemm()));
			disLink = (price.getDislink() == null) ? "" : price.getDislink();
			String ls_dis_name = ServiceManager.getInstance().mDiscountSettingService
					.getItemDiscountName(disLink.equals("") ? "0" : disLink);
			btn_dis_link.setText((ls_dis_name == null) ? "" : String
					.valueOf(ls_dis_name));
		}
	}

	public void setempty() {
		et_da_price.setText("");
		et_et_date.setText("");
		et_et_time.setText("");
		et_lq_amt.setText("");
		et_lq_price.setText("");
		et_np_amt.setText("");
		et_np_price.setText("");
		et_percent_amt.setText("");
		et_pp_amt.setText("");
		et_pp_price.setText("");
		et_st_date.setText("");
		et_st_time.setText("");
		btn_mm.setText("");
	}

	public String getdatetime(String date) {
		Date curDate = null;
		String str;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		DateFormat format1 = new SimpleDateFormat("yyyyMMdd");
		try {
			if (date == null) {
				return "";
			}
			curDate = format1.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (curDate == null) {
			str = "";
		} else {
			str = formatter.format(curDate);
		}
		return str;
	};

	public String gettime(String time) {
		if (time == null || time.equals("")) {
			return "";
		} else {
			String str = time.substring(0, 2);
			String str2 = time.substring(2);
			return str + ":" + str2;
		}
	};

	public void setdate(int id) {
		EditText et_date = (EditText) priceDialog.findViewById(id);
		String ls_date = et_date.getText().toString();
		Date curDate = null;
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		try {
			curDate = (Date) format1.parse(ls_date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar c1 = Calendar.getInstance();
		if (curDate == null) {
			mYear = c1.get(Calendar.YEAR);
			mMonth = c1.get(Calendar.MONTH);
			mDay = c1.get(Calendar.DAY_OF_MONTH);
		} else {
			c1.setTime(curDate);
			mYear = c1.get(Calendar.YEAR);
			mMonth = c1.get(Calendar.MONTH);
			mDay = c1.get(Calendar.DAY_OF_MONTH);
		}
	}

	public void settime(int id) {
		EditText et_time = (EditText) priceDialog.findViewById(id);
		String ls_time = et_time.getText().toString();
		if (ls_time.equals("") || ls_time == null) {
			Calendar c1 = Calendar.getInstance();
			hour = c1.get(Calendar.HOUR_OF_DAY);
			minute1 = c1.get(Calendar.MINUTE);
		} else {
			String hourOfDay = ls_time.substring(0, 2);
			String minute = ls_time.substring(3);

			hour = Integer.valueOf(hourOfDay);
			minute1 = Integer.valueOf(minute);
		}
	}

	OnDateSetListener mDateSetListener = new OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			String date;
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			date = (new StringBuilder().append(mYear).append("-")
					.append(String.format("%02d", mMonth + 1)).append("-")
					.append(String.format("%02d", mDay))).toString();
			if (datetype.equals("st_date")) {
				et_st_date.setText(date);
				if (et_st_time.getText().toString().equals("")) {
					et_st_time.setText("00:00");
				}
			} else {
				et_et_date.setText(date);

				if (et_et_time.getText().toString().equals("")) {
					et_et_time.setText("23:59");
				}
			}
		}
	};

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID_S:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		case DATE_DIALOG_ID_E:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		case TIME_DIALOG_ID_S:
			return new TimePickerDialog(this, mTimeSetListener, hour, minute1,
					true);
		case TIME_DIALOG_ID_E:
			return new TimePickerDialog(this, mTimeSetListener, hour, minute1,
					true);
		}
		return null;
	};

	@Override
	public void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case DATE_DIALOG_ID_S:
			removeDialog(DATE_DIALOG_ID_S);
			break;
		case DATE_DIALOG_ID_E:
			removeDialog(DATE_DIALOG_ID_E);
			break;
		case TIME_DIALOG_ID_S:
			removeDialog(TIME_DIALOG_ID_S);
			break;
		case TIME_DIALOG_ID_E:
			removeDialog(TIME_DIALOG_ID_E);
			break;

		}
	}

	OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			String time;
			hour = hourOfDay;
			minute1 = minute;
			Calendar c1 = Calendar.getInstance();
			mYear = c1.get(Calendar.YEAR);
			mMonth = c1.get(Calendar.MONTH) + 1;
			mDay = c1.get(Calendar.DAY_OF_MONTH);
			time = String.format("%02d", hour) + ":"
					+ String.format("%02d", minute1);

			if (timetype.equals("st_time")) {
				et_st_time.setText(time);
				et_st_date.setText(mYear + "-" + String.format("%02d", mMonth) + "-" + mDay);
			} else {
				et_et_time.setText(time);
				et_et_date.setText(mYear + "-" + String.format("%02d", mMonth) + "-" + mDay);
			}
		}

	};

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		String Path = "";
		try {
			if (is_import_data) {
				Bundle bundle = data.getExtras();
				Path = bundle.getString("path");
				filePathString = bundle.getString("filePath");
				is_import_data = false;
				et_path.setText(Path);
				Path = "";
				return;
			} else {
				Bundle bundle = data.getExtras();
				Path = bundle.getString("path");
				imagePath = bundle.getString("imagePath");
			}
		} catch (Exception e) {
			Path = "";
		}
		if (Path != "") {
			try {
				PathString = Path;
				byte[] by = ImageUtil.zonmImageFile(Path, 400, 300);
				iv_image.setImageBitmap(ImageUtil.btyes2Bitmap(by));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Path = "";
	}

	OnClickListener onClickPopupWindowListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.btn_browse:
				Intent intent = new Intent();
				intent.putExtra("imagePath", imagePath);
				intent.setClass(ItemSettingActivity.this,
						FilePickerActivity.class);
				ItemSettingActivity.this.startActivityForResult(intent,
						CONTEXT_RESTRICTED);
				break;
			case R.id.btn_ok:
				int index = listAdapter.GetSelectedIndex();
				String upc = String.valueOf(listitem.get(index).getUpc());
				byte[] by;
				byte[] by2;
				Bitmap bitmap = mItemPicService.getImageByUPC(upc);
				if (bitmap != null) {
					try {
						if (PathString != "") {
							by = ImageUtil.zonmImageFile(PathString, 400, 300);
							by2 = ImageUtil.zonmImageFile(PathString, 120, 90);
							int i = ServiceManager.getInstance().mPicService
									.ImageUpdate(upc, by, by2);
							if (GlobalInfo.getInstance().isMGNetwork) {
								Bitmap bp = mItemPicService.getImageByUPC(upc);
								Bitmap bp2 = mItemPicService.getImageSmByUPC(upc);
								FileOutputStream out = new FileOutputStream("/mnt/sdcard/moleq/cache/" + upc + ".jpg");
								FileOutputStream out2 = new FileOutputStream("/mnt/sdcard/moleq/cache/" + upc + "_sm.jpg");
								bp.compress(Bitmap.CompressFormat.JPEG, 90,out);
								bp2.compress(Bitmap.CompressFormat.JPEG, 90, out2);
//								String sby = new String(by);
//								String sby2 = new String(by2);
								ItemPic itemPic = new ItemPic();
								itemPic.setUpc(upc);
								itemPic.setIp_image(upc + ".jpg");
								itemPic.setIp_image_sm(upc + "_sm.jpg");
								mMGCreateFiles.createrFile(itemPic
										.toMGData("UPDATE"));// UPDATE,DELETE
							}
							PathString = "";
							if (i == 1) {
								MessageBox.show(ItemSettingActivity.this,
										"Execution Completed.",
										onClickMessageListener,
										MessageDialog.MESSAGE_BOX_OK);
								
								
							} else {
								MessageBox.show(ItemSettingActivity.this,
										"Execution Failure.",
										onClickMessageListener,
										MessageDialog.MESSAGE_BOX_OK);
							}
							
						}
						dialog.dismiss();
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					try {
						if (PathString != "") {
							by = ImageUtil.zonmImageFile(PathString, 400, 300);
							by2 = ImageUtil.zonmImageFile(PathString, 120, 90);
							ServiceManager.getInstance().mPicService
									.ImageInsert(upc, by, by2);
							if (GlobalInfo.getInstance().isMGNetwork) {
								Bitmap bp = mItemPicService.getImageByUPC(upc);
								Bitmap bp2 = mItemPicService.getImageSmByUPC(upc);
								FileOutputStream out = new FileOutputStream("/mnt/sdcard/moleq/cache/" + upc + ".jpg");
								FileOutputStream out2 = new FileOutputStream("/mnt/sdcard/moleq/cache/" + upc + "_sm.jpg");
								bp.compress(Bitmap.CompressFormat.JPEG, 90,out);
								bp2.compress(Bitmap.CompressFormat.JPEG, 90, out2);
//								String sby = new String(by);
//								String sby2 = new String(by2);
								ItemPic itemPic = new ItemPic();
								itemPic.setUpc(upc);
								itemPic.setIp_image(upc + ".jpg");
								itemPic.setIp_image_sm(upc + "_sm.jpg");
								mMGCreateFiles.createrFile(itemPic
										.toMGData("INSERT"));// UPDATE,DELETE
							}
							PathString = "";
							MessageBox.show(ItemSettingActivity.this,
									"Execution Completed.",
									onClickMessageListener,
									MessageDialog.MESSAGE_BOX_OK);
						}
						dialog.dismiss();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				Bitmap bp = mItemPicService.getImageByUPC(upc);
				iv_photo.setImageBitmap(bp);
				if (bp == null) {
					Bitmap logo = BitmapFactory.decodeResource(
							ItemSettingActivity.this.getApplicationContext()
									.getResources(), R.drawable.moleqlogo);
					iv_photo.setImageBitmap(logo);
				} else {
					iv_photo.setImageBitmap(bp);
				}
				break;
			case R.id.btn_cancel:
				ChangeMode.mode = 0;
				String upcc = String.valueOf(listitem.get(
						listAdapter.GetSelectedIndex()).getUpc());
				GetItemDetail(upcc);
				ChangeMode.mode = 1;
				dialog.dismiss();
				break;
			case R.id.iv_clean_img:
				isImg = true;
				MessageBox.show(ItemSettingActivity.this,
						"Are you sure to remove this picture?",
						onClickMessageListener,
						MessageDialog.MESSAGE_BOX_YES_NO);
				break;
			case R.id.btn_net_wt_ok:
				if (NetWTList.size() > 0) {
					et_net_wt_search = (EditText) netWtDialog
							.findViewById(R.id.et_net_wt_search);
					btn_net_wt.setText(String.valueOf(NetWTList.get(
							netWTAdapter.GetSelectedIndex()).getUd_short()));
					et_net_wt_search.setText("");
					SetEnabledFalse();
					SetNetWTDataSource("");
				}
				netWtDialog.dismiss();
				break;
			case R.id.btn_net_wt_cancel:
				et_net_wt_search = (EditText) netWtDialog
						.findViewById(R.id.et_net_wt_search);
				et_net_wt_search.setText("");
				SetNetWTDataSource("");
				netWtDialog.dismiss();
				break;
			case R.id.btn_net_wt_search:
				et_net_wt_search = (EditText) netWtDialog
						.findViewById(R.id.et_net_wt_search);
				ListView lv_net_wt_list = (ListView) netWtDialog
						.findViewById(R.id.lv_net_wt_list);
				String net_wt_search = String.valueOf(et_net_wt_search
						.getText());
				if (net_wt_search.trim().equals("")) {
					SetNetWTDataSource("");
				} else {
					SetNetWTDataSource(net_wt_search);
				}
				netWTAdapter.setSource(NetWTList);
				netWTAdapter.notifyDataSetChanged();
				netWTAdapter.ScrollToRow(0);
				lv_net_wt_list.setSelection(0);
				et_net_wt_search.setText("");
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(et_net_wt_search.getWindowToken(),
						0);
				break;
			case R.id.btn_dept_ok:
				if (DeptList.size() > 0) {
					int Depindex = deptAdapter.GetSelectedIndex();
					if (Depindex >= 0 && Depindex <= DeptList.size()) {
						btn_dep.setText(String.valueOf(DeptList.get(Depindex)
								.getSd_name()));
					}
				}
				deptDialog.dismiss();
				break;
			case R.id.btn_dept_cancel:
				deptDialog.dismiss();
				break;
			case R.id.btn_price_setting_save:
				if (validation() < 0) {
					return;
				}
				String upc2,
				cp_price,
				cp_amt,
				da_price,
				et_date,
				et_time,
				lq_amt,
				lq_price,
				np_amt,
				np_price,
				percent_amt,
				pp_amt,
				pp_price,
				st_date,
				st_time,
				pmm;
				upc2 = et_upc.getText().toString();
				cp_price = et_cp_price.getText().toString();
				cp_amt = et_cp_amt.getText().toString();
				da_price = et_da_price.getText().toString();
				et_date = et_et_date.getText().toString();
				et_time = et_et_time.getText().toString();
				lq_amt = et_lq_amt.getText().toString();
				lq_price = et_lq_price.getText().toString();
				np_amt = et_np_amt.getText().toString();
				np_price = et_np_price.getText().toString();
				percent_amt = et_percent_amt.getText().toString();
				pp_amt = et_pp_amt.getText().toString();
				pp_price = et_pp_price.getText().toString();
				st_date = et_st_date.getText().toString();
				st_time = et_st_time.getText().toString();
				pmm = btn_mm.getText().toString();
				PriceSetting price = new PriceSetting();
				MixMatch mm = new MixMatch();
				if (dis != null) {
					disLink = String.valueOf(dis.getDs_no());
				}
				price.setUpc(upc2);
				price.setPriceMultiple((!np_price.equals("")) ? (np_amt
						.equals("")) ? "1" : String.valueOf(np_amt) : null);
				price.setPrice((np_price.equals("")) ? null : String
						.valueOf(np_price));
				price.setStartdate(st_date);
				price.setStarttime(st_time);
				price.setEnddate(et_date);
				price.setEndtime(et_time);
				price.setPackagepricemultiple((!pp_price.equals("")) ? (pp_amt
						.equals("")) ? "1" : String.valueOf(pp_amt) : null);
				price.setPackageprice((pp_price.equals("")) ? null : String
						.valueOf(pp_price));
				price.setLimitedqtyamount((!lq_price.equals("")) ? (lq_amt
						.equals("")) ? "1" : String.valueOf(lq_amt) : null);
				price.setLimitedqtyprice((lq_price.equals("")) ? null : String
						.valueOf(lq_price));
				price.setDiscountamount((da_price.equals("")) ? null : String
						.valueOf(da_price));
				price.setDiscountpercent((percent_amt.equals("")) ? null
						: String.valueOf(percent_amt));
				price.setPricemm((pmm.equals("")) ? null : String.valueOf(pmm));
				price.setDislink((disLink.equals("")) ? null : disLink);
				mm.setUpc(upc2);
				mm.setMm_no((pmm.equals("")) ? 0 : Integer.valueOf(pmm));
				PriceSetting mPriceSetting = null;
				if (price_type.equals("1")) {
					mItemSettingService.updatePrice(cp_price, cp_amt, upc2);
					if (GlobalInfo.getInstance().isMGNetwork) {
						ItemSetting mItemSetting = mItemSettingService.findByUpc(upc2);
						if (mItemSetting != null) {
							mMGCreateFiles.createrFile(mItemSetting
									.toMGData("UPDATE"));// UPDATE,DELETE
						}
					}
				}
				if (mPriceService.checkitemprice(upc2) == false) {
					mPriceService.InsertPrice(price);
					if (GlobalInfo.getInstance().isMGNetwork) {
						mPriceSetting = mPriceService.getitempricesetting(upc2);
						mMGCreateFiles.createrFile(mPriceSetting
								.toMGData("INSERT"));// UPDATE,DELETE
					}
					Toast.makeText(ItemSettingActivity.this, "Save completed.",
							Toast.LENGTH_SHORT).show();
					ChangeMode.mode = 0;
					GetItemDetail(upc2);
					ChangeMode.mode = 1;
					if (priceDialog != null)
						priceDialog.dismiss();
				} else {
					mPriceService.UpdatePriceSetting(price);
					if (GlobalInfo.getInstance().isMGNetwork) {
						mPriceSetting = mPriceService.getitempricesetting(upc2);
						if (mPriceSetting != null) {
							mMGCreateFiles.createrFile(mPriceSetting
									.toMGData("UPDATE"));// UPDATE,DELETE
						}
					}
					Toast.makeText(ItemSettingActivity.this, "Save completed.",
							Toast.LENGTH_SHORT).show();
					ChangeMode.mode = 0;
					GetItemDetail(upc2);
					ChangeMode.mode = 1;
					if (priceDialog != null)
						priceDialog.dismiss();
				}
				if (!mMixMatchService.checkMixMatch(upc2)) {
					mMixMatchService.InsertMixMatch(mm);
					if (GlobalInfo.getInstance().isMGNetwork) {
						MixMatch mMixMatch = mMixMatchService.FindMmByUPC(upc2);
						if (mMixMatch != null) {
							mMGCreateFiles.createrFile(mMixMatch
									.toMGData("INSERT"));// UPDATE,DELETE
						}
					}
				} else {
//					mMixMatchService.UpdateMixMatch(mm);
//					if (GlobalInfo.getInstance().isMGNetwork) {
//						MixMatch mMixMatch = mMixMatchService.FindMmByUPC(upc2);
//						if (mMixMatch != null) {
//							mMGCreateFiles.createrFile(mMixMatch
//									.toMGData("UPDATE"));// UPDATE,DELETE
//						}
//					}
					if (pmm.equals("")) {
						if (GlobalInfo.getInstance().isMGNetwork) {
							MixMatch mMixMatch = mMixMatchService
									.FindMmByUPC(upc2);
							if (mMixMatch != null) {
								mMGCreateFiles.createrFile(mMixMatch
										.toMGData("DELETE"));// UPDATE,DELETE
							}
						}
						mMixMatchService.DeleteMm(upc2);
					}else{
						mMixMatchService.UpdateMixMatch(mm);
						if (GlobalInfo.getInstance().isMGNetwork) {
							MixMatch mMixMatch = mMixMatchService.FindMmByUPC(upc2);
							if (mMixMatch != null) {
								mMGCreateFiles.createrFile(mMixMatch
										.toMGData("UPDATE"));// UPDATE,DELETE
							}
						}
					}
				}
				if (da_price.trim().equals("") && et_date.trim().equals("")
						&& et_time.trim().equals("")
						&& lq_amt.trim().equals("")
						&& lq_price.trim().equals("")
						&& np_amt.trim().equals("")
						&& np_price.trim().equals("")
						&& percent_amt.trim().equals("")
						&& pp_amt.trim().equals("")
						&& pp_price.trim().equals("")
						&& st_date.trim().equals("")
						&& st_time.trim().equals("") && pmm.trim().equals("")
						&& disLink.trim().equals("")) {
					mPriceSetting = mPriceService.getitempricesetting(upc2);
					mPriceService.DeletePriceSetting(upc2);
					if (GlobalInfo.getInstance().isMGNetwork) {
						if (GlobalInfo.getInstance().isMGNetwork) {
							if (mPriceSetting != null) {
								mMGCreateFiles.createrFile(mPriceSetting
										.toMGData("DELETE"));// UPDATE,DELETE
							}
						}
					}
				}
				price_type = "0";
				SetPriceEnabledTrue();
				break;
			case R.id.btn_price_setting_back:
				priceDialog.dismiss();
				break;
			case R.id.btn_tare_ok:
				itemTareList.clear();
				btn_single_tare.setText("");
				String strTare = tareItems.get(tareChooseAdapter.GetSelectedIndex());
				btn_tare.setText(strTare);
				TareImageView(strTare);
				tareDialog.dismiss();
				break;
			case R.id.btn_tare_cancel:
				tareDialog.dismiss();
				break;
			case R.id.btn_tare_setting_ok:
				if (tareSettingList.size() > 0) {
					if (String.valueOf(btn_tare.getText()).equals("Multiple")) {
						if (itemTareList.size() > 0) {
							for (int i = 0; i < itemTareList.size(); i++) {
								String s1, s2;
								s1 = itemTareList.get(i).getDesc();
								s2 = tareSettingList.get(
										tareSettingAdapter.GetSelectedIndex())
										.getTa_desc();
								if (s1.equals(s2)) {
									tareSettingDialog.dismiss();
									return;
								}
							}
						}
						ItemTareSetting item = new ItemTareSetting();
						item.setIt_no(itemTareList.size() + 1);
						item.setDesc(tareSettingList.get(
								tareSettingAdapter.GetSelectedIndex())
								.getTa_desc());
						item.setIt_tare_no(tareSettingList.get(
								tareSettingAdapter.GetSelectedIndex())
								.getTa_no());
						item.setValue(String.valueOf(tareSettingList.get(
								tareSettingAdapter.GetSelectedIndex())
								.getTotalTare()));
						item.setUpc(String.valueOf(et_upc.getText()));
						itemTareList.add(item);
						tareSelectionAdapter.setSource(itemTareList);
						tareSelectionAdapter.notifyDataSetChanged();
						tareSelectionAdapter
								.ScrollToRow(itemTareList.size() - 1);
					} else if (String.valueOf(btn_tare.getText()).equals(
							"Single")) {
						btn_single_tare.setText(tareSettingList.get(
								tareSettingAdapter.GetSelectedIndex())
								.getTa_desc());
					}
				}
				tareSettingDialog.dismiss();
				break;
			case R.id.btn_tare_setting_cancel:
				tareSettingDialog.dismiss();
				break;
			case R.id.btn_bottle_deposit_ok:
				if (bottleList.size() > 0) {
					btn_bottle_deposit.setText(bottleList.get(
							bottleAdapter.GetSelectedIndex()).getBo_desc());
				}
				bottleDialog.dismiss();
				break;
			case R.id.btn_bottle_deposit_cancel:
				bottleDialog.dismiss();
				break;
			case R.id.btn_printer_ok:
				if (printerList.size() > 0) {
					int index2 = printerAdapter.GetSelectedIndex();
					if(index2 < 0){
						btn_printer.setText("None");
						btn_printer.setTag(null);
					}else{
						PrinterSetting item = printerList.get(index2);
						btn_printer.setText(item.getPs_name());
						btn_printer.setTag(item);
					}
				}else{
					btn_printer.setText("None");
					btn_printer.setTag(null);
				}
				printerDialog.dismiss();
				break;
			case R.id.btn_printer_cancel:
				printerDialog.dismiss();
				break;
//			case R.id.btn_age_dialog_ok:
//				if (ageList.size() > 0) {
//					btn_age_ver.setText(ageList.get(
//							ageAdapter.GetSelectedIndex()).getAs_desc());
//					btn_age_ver.setTag(ageList.get(ageAdapter
//							.GetSelectedIndex()));
//				} else {
//					btn_age_ver.setText("");
//					btn_age_ver.setTag(null);
//				}
//				ageDialog.dismiss();
//				break;
//			case R.id.btn_age_dialog_cancel:
//				ageDialog.dismiss();
//				break;
//			case R.id.iv_age_dialog_add:
//				et_age_name.setText("");
//				et_age_value.setText("");
//				et_age_name.setVisibility(View.VISIBLE);
//				et_age_value.setVisibility(View.VISIBLE);
//				iv_age_dialog_add.setVisibility(View.GONE);
//				iv_age_dialog_complete.setVisibility(View.VISIBLE);
//				iv_age_dialog_delete.setEnabled(false);
//				iv_age_dialog_update.setEnabled(false);
//				lv_age_dialog_list.setEnabled(false);
//				btn_age_dialog_ok.setEnabled(false);
//				btn_age_dialog_cancel.setEnabled(false);
//				break;
//			case R.id.iv_age_dialog_ok:
//				String nameString = String.valueOf(et_age_name.getText());
//				String ageString = String.valueOf(et_age_value.getText());
//				if (ageList.size() > 0) {
//					if (!nameString.trim().equals("")
//							&& !ageString.trim().equals("")) {
//						String nameString2 = ageList.get(
//								ageAdapter.GetSelectedIndex()).getAs_desc();
//						String ageString2 = String.valueOf(ageList.get(
//								ageAdapter.GetSelectedIndex()).getAs_age());
//						if (!(nameString.equals(nameString2)
//								&& ageString.equals(ageString2) && is_age_edit)) {
//							if (!mAgeSettingService.CheckAge(ageString,
//									nameString)) {
//								MessageBox.show(ItemSettingActivity.this,
//										"Already exist for this Item.",
//										onClickMessageListener,
//										MessageDialog.MESSAGE_BOX_OK);
//								return;
//							}
//						}
//					}
//				}
//				AgeSetting item = null;
//				if (is_age_edit) {
//					if (nameString.trim().equals("")) {
//						MessageBox.show(ItemSettingActivity.this,
//								"Please enter the age name.",
//								onClickMessageListener,
//								MessageDialog.MESSAGE_BOX_OK);
//						return;
//					}
//					if (ageString.trim().equals("")) {
//						MessageBox.show(ItemSettingActivity.this,
//								"Please enter the age.",
//								onClickMessageListener,
//								MessageDialog.MESSAGE_BOX_OK);
//						return;
//					}
//					int age = Integer.valueOf(String.valueOf(et_age_value
//							.getText()));
//					String name = String.valueOf(et_age_name.getText());
//					int no = ageList.get(ageAdapter.GetSelectedIndex())
//							.getAs_no();
//					item = mAgeSettingService.Find(no);
//					item.setAs_no(no);
//					item.setAs_desc(name);
//					item.setAs_age(age);
//					item.setCreate_datetime(MoleQUtil.getDateToString(
//							"yyyyMMddHHmmss", now));
//					mAgeSettingService.Update(item);
//					ageList = mAgeSettingService.FindAll();
//					ageAdapter.setSource(ageList);
//					ageAdapter.notifyDataSetChanged();
//					if (GlobalInfo.getInstance().isMGNetwork) {
//						mMGCreateFiles.createrFile(item.toMGData("UPDATE"));
//					}
//				} else {
//					if (ageList.size() <= 0)
//						ageAdapter.ScrollToRow(0);
//					if (!nameString.trim().equals("")
//							&& !ageString.trim().equals("")) {
//						item = new AgeSetting();
//						item.setAs_no(mAgeSettingService.FindMaxNo());
//						item.setAs_desc(String.valueOf(et_age_name.getText()));
//						item.setAs_age(Integer.valueOf(String
//								.valueOf(et_age_value.getText())));
//						item.setCreate_datetime(MoleQUtil.getDateToString(
//								"yyyyMMddHHmmss", now));
//						item.setUpdate_datetime(MoleQUtil.getDateToString(
//								"yyyyMMddHHmmss", now));
//						mAgeSettingService.Insert(item);
//						ageList = mAgeSettingService.FindAll();
//						ageAdapter.setSource(ageList);
//						ageAdapter.notifyDataSetChanged();
//						if (GlobalInfo.getInstance().isMGNetwork) {
//							mMGCreateFiles.createrFile(item.toMGData("INSERT"));
//						}
//					}
//				}
//				et_age_name.setVisibility(View.GONE);
//				et_age_value.setVisibility(View.GONE);
//				iv_age_dialog_add.setVisibility(View.VISIBLE);
//				iv_age_dialog_complete.setVisibility(View.GONE);
//				is_age_edit = false;
//				iv_age_dialog_delete.setEnabled(true);
//				iv_age_dialog_update.setEnabled(true);
//				lv_age_dialog_list.setEnabled(true);
//				btn_age_dialog_ok.setEnabled(true);
//				btn_age_dialog_cancel.setEnabled(true);
//				break;
//			case R.id.iv_age_dialog_delete:
//				if (ageList.size() <= 0)
//					return;
//				if (mItemSettingService.CheckAgeNo(ageList.get(
//						ageAdapter.GetSelectedIndex()).getAs_no())) {
//					MessageBox
//							.show(ItemSettingActivity.this,
//									"The age setting cannot be removed because it is linked to items or departments.",
//									onClickMessageListener,
//									MessageDialog.MESSAGE_BOX_OK);
//					return;
//				}
//				int index1 = ageAdapter.GetSelectedIndex();
//				int index2 = -1;
//				if (index1 == 0 && ageList.size() > 1) {
//					index2 = index1;
//				} else if (index1 > 0) {
//					index2 = index1 - 1;
//				}
//				item = mAgeSettingService.Find(ageList.get(
//						ageAdapter.GetSelectedIndex()).getAs_no());
//				mAgeSettingService.DeleteAge(ageList.get(
//						ageAdapter.GetSelectedIndex()).getAs_no());
//				if (GlobalInfo.getInstance().isMGNetwork) {
//					mMGCreateFiles.createrFile(item.toMGData("DELETE"));
//				}
//				ageList = mAgeSettingService.FindAll();
//				ageAdapter.setSource(ageList);
//				ageAdapter.notifyDataSetChanged();
//				ageAdapter.ScrollToRow(index2);
//				break;
//			case R.id.iv_age_dialog_update:
//				if (ageList.size() <= 0)
//					return;
//				is_age_edit = true;
//				et_age_name.setText(String.valueOf(ageList.get(
//						ageAdapter.GetSelectedIndex()).getAs_desc()));
//				et_age_value.setText(String.valueOf(ageList.get(
//						ageAdapter.GetSelectedIndex()).getAs_age()));
//				et_age_name.setVisibility(View.VISIBLE);
//				et_age_value.setVisibility(View.VISIBLE);
//				iv_age_dialog_add.setVisibility(View.GONE);
//				iv_age_dialog_complete.setVisibility(View.VISIBLE);
//				iv_age_dialog_delete.setEnabled(false);
//				iv_age_dialog_update.setEnabled(false);
//				lv_age_dialog_list.setEnabled(false);
//				btn_age_dialog_ok.setEnabled(false);
//				btn_age_dialog_cancel.setEnabled(false);
//				break;
			}
		}
	};

	public void SetTextChange() {
		et_upc.addTextChangedListener(new EditTextMaxLengthWatcher(20, et_upc,
				ItemSettingActivity.this));
		et_name.addTextChangedListener(new EditTextMaxLengthWatcher(50,
				et_name, ItemSettingActivity.this));
		et_desc.addTextChangedListener(new EditTextMaxLengthWatcher(50,
				et_desc, ItemSettingActivity.this));
		et_price.addTextChangedListener(new EditTextMaxLengthWatcher(3,
				et_price, ItemSettingActivity.this));
		et_price_2.addTextChangedListener(new EditTextMaxLengthWatcher(8,
				et_price_2, ItemSettingActivity.this));
		et_wt.addTextChangedListener(new EditTextMaxLengthWatcher(7, et_wt,
				ItemSettingActivity.this));
		et_vdr.addTextChangedListener(new EditTextMaxLengthWatcher(10, et_vdr,
				ItemSettingActivity.this));
		et_sub_dept.addTextChangedListener(new EditTextMaxLengthWatcher(4,
				et_sub_dept, ItemSettingActivity.this));
		et_case_pack_size.addTextChangedListener(new EditTextMaxLengthWatcher(
				4, et_case_pack_size, ItemSettingActivity.this));
		et_case_cost.addTextChangedListener(new EditTextMaxLengthWatcher(9,
				et_case_cost, ItemSettingActivity.this));
		et_upc.addTextChangedListener(watcher);
		et_name.addTextChangedListener(watcher);
		et_desc.addTextChangedListener(watcher);
		et_price.addTextChangedListener(watcher);
		et_price_2.addTextChangedListener(watcher);
		et_wt.addTextChangedListener(watcher);
		btn_dep.addTextChangedListener(watcher);
		btn_net_wt.addTextChangedListener(watcher);
		et_vdr.addTextChangedListener(watcher);
		et_sub_dept.addTextChangedListener(watcher);
		et_case_pack_size.addTextChangedListener(watcher);
		et_case_cost.addTextChangedListener(watcher);
		btn_tare.addTextChangedListener(watcher);
		btn_single_tare.addTextChangedListener(watcher);
	}

	public void InitializeEnabledFalse() {
		et_upc.setEnabled(false);
		et_name.setEnabled(false);
		et_desc.setEnabled(false);
		et_price.setEnabled(false);
		et_price_2.setEnabled(false);
		et_wt.setEnabled(false);
		btn_net_wt.setEnabled(false);
		cb_active.setEnabled(false);
		btn_dep.setEnabled(false);
		et_vdr.setEnabled(false);
		et_sub_dept.setEnabled(false);
		et_case_pack_size.setEnabled(false);
		et_case_cost.setEnabled(false);
		btn_next.setVisibility(View.INVISIBLE);
		btn_back.setVisibility(View.INVISIBLE);
		btn_del.setEnabled(false);
		iv_price_setting.setEnabled(false);
		cb_tax_1.setEnabled(false);
		cb_tax_2.setEnabled(false);
		cb_tax_3.setEnabled(false);
		cb_tax_4.setEnabled(false);
		cb_tax_5.setEnabled(false);
		cb_tax_6.setEnabled(false);
		cb_follow_dept.setEnabled(false);
		cb_no_discnt.setEnabled(false);
		cb_food_stamp.setEnabled(false);
		cb_scale_weight.setEnabled(false);
		cb_age_ver.setEnabled(false);
		cb_wic.setEnabled(false);
		cb_cvv.setEnabled(false);
		cb_bottle_deposit.setEnabled(false);
		cb_loyalty.setEnabled(false);
		cb_coupon.setEnabled(false);
		cb_printer.setEnabled(false);
		cb_mult_coupon.setEnabled(false);
		btn_tare.setEnabled(false);
		btn_single_tare.setVisibility(View.INVISIBLE);
		lv_tare.setVisibility(View.INVISIBLE);
		btn_bottle_deposit.setVisibility(View.INVISIBLE);
		iv_tare_del.setVisibility(View.INVISIBLE);
		iv_tare_add.setVisibility(View.INVISIBLE);
		tv_tare_background.setVisibility(View.INVISIBLE);
		tv_page.setText("");
		tv_send_to_printer.setVisibility(View.INVISIBLE);
		btn_printer.setVisibility(View.INVISIBLE);
	}

	public void InitializeEnabledTrue() {
		et_name.setEnabled(true);
		et_desc.setEnabled(true);
		et_price.setEnabled(true);
		et_price_2.setEnabled(true);
		et_wt.setEnabled(true);
		btn_net_wt.setEnabled(true);
		cb_active.setEnabled(true);
		btn_dep.setEnabled(true);
		et_vdr.setEnabled(true);
		et_sub_dept.setEnabled(true);
		et_case_pack_size.setEnabled(true);
		et_case_cost.setEnabled(true);
		cb_bottle_deposit.setEnabled(true);
		cb_loyalty.setEnabled(true);
		cb_coupon.setEnabled(true);
		cb_printer.setEnabled(true);
		cb_mult_coupon.setEnabled(true);
		btn_tare.setEnabled(true);
		btn_add.setEnabled(true);
		btn_del.setEnabled(true);
		iv_price_setting.setEnabled(true);

	}

	public void ControlEmpty() {
		et_upc.setText("");
		et_name.setText("");
		et_desc.setText("");
		et_price.setText("");
		et_price_2.setText("");
		et_wt.setText("");
		cb_active.setChecked(false);
		btn_dep.setText("");
		et_vdr.setText("");
		et_sub_dept.setText("");
		et_case_pack_size.setText("");
		et_case_cost.setText("");
		cb_tax_1.setChecked(false);
		cb_tax_2.setChecked(false);
		cb_tax_3.setChecked(false);
		cb_tax_4.setChecked(false);
		cb_tax_5.setChecked(false);
		cb_tax_6.setChecked(false);
		cb_follow_dept.setChecked(false);
		cb_no_discnt.setChecked(false);
		cb_food_stamp.setChecked(false);
		cb_scale_weight.setChecked(false);
		cb_age_ver.setChecked(false);
		cb_wic.setChecked(false);
		cb_cvv.setChecked(false);
		cb_bottle_deposit.setChecked(false);
		cb_loyalty.setChecked(false);
		cb_coupon.setChecked(false);
		cb_printer.setChecked(false);
		cb_mult_coupon.setChecked(false);
		btn_printer.setText("None");
		btn_printer.setTag(null);
		btn_net_wt.setText("");
		btn_tare.setText("");
		Bitmap logo = BitmapFactory.decodeResource(ItemSettingActivity.this
				.getApplicationContext().getResources(), R.drawable.moleqlogo);
		iv_photo.setImageBitmap(logo);
	}

	@Override
	public void onErrorEvent(String res) {
	}

	@Override
	public void onScannerEvent(String res) {
		if (SaveMode == "Insert") {
			et_upc.setText(res);
		} else if (SaveMode == "Update") {
			return;
		} else {
			sp_list.setSelection(SP.UPC);
			et_search.setEnabled(true);
			UPC upc = new UPC(res, UPC.INPUT_BY_MANUAL,
					GlobalInfo.getInstance().isNormalize);
			res = upc.code;
			et_search.setText(res);
			Keyboard();
			tv_page.setText(String.valueOf(1));
			ChangeMode.mode = 0;
			this.Search();
			ChangeMode.mode = 1;
			et_search.setText("");
			btn_undo.setEnabled(false);
			btn_save.setEnabled(false);
			btn_exit.setEnabled(true);
			btn_add.setEnabled(true);
			btn_search.setEnabled(true);
		}
	}

	@Override
	public void onWeightEvent(int res) {
	}

	@Override
	public void onTimeOutEvent() {
	}

	public void FollowDeptCheckedTrue() {
		cb_tax_1.setEnabled(false);
		cb_tax_2.setEnabled(false);
		cb_tax_3.setEnabled(false);
		cb_tax_4.setEnabled(false);
		cb_tax_5.setEnabled(false);
		cb_tax_6.setEnabled(false);
		cb_no_discnt.setEnabled(false);
		cb_food_stamp.setEnabled(false);
		cb_scale_weight.setEnabled(false);
		cb_age_ver.setEnabled(false);
		cb_wic.setEnabled(false);
		cb_cvv.setEnabled(false);
	}

	public void FollowDeptCheckedFalse() {
		cb_tax_1.setEnabled(true);
		cb_tax_2.setEnabled(true);
		cb_tax_3.setEnabled(true);
		cb_tax_4.setEnabled(true);
		cb_tax_5.setEnabled(true);
		cb_tax_6.setEnabled(true);
		cb_no_discnt.setEnabled(true);
		cb_food_stamp.setEnabled(true);
		cb_scale_weight.setEnabled(true);
		cb_age_ver.setEnabled(true);
		cb_wic.setEnabled(true);
		cb_cvv.setEnabled(true);
	}

	public String repeatString(String s, int n) {
		return String.format(String.format("%%0%dd", n), 0).replace("0", s);
	}

	private OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {
			if (isDelete) {
				String upc = "";
				int index = listAdapter.GetSelectedIndex();
				int index2 = -1;
				if (index == 0 && listitem.size() > 1) {
					index2 = index;
					upc = String.valueOf(listitem.get(index2 + 1).getUpc());
				} else if (index > 0) {
					index2 = index - 1;
					upc = String.valueOf(listitem.get(index2).getUpc());
				}
				Delete();
				ChangeMode.mode = 0;
				if (!upc.equals("")) {
					GetItemDetail(upc);
				} else {
					ControlEmpty();
					listitem.clear();
					listAdapter.setSource(listitem);
					listAdapter.notifyDataSetChanged();
				}
				ChangeMode.mode = 1;
				listAdapter.ScrollToRow(index2);
				if (listitem.size() <= 0) {
					InitializeEnabledFalse();
					FollowDeptCheckedTrue();
					cb_follow_dept.setEnabled(false);
				}
				isDelete = false;
				mDeviceManager.clearAllScannerBuffer();
				mDeviceManager.enableAllScanner();
			} else if (isImg) {
				Bitmap logo = BitmapFactory.decodeResource(
						ItemSettingActivity.this.getApplicationContext()
								.getResources(), R.drawable.moleqlogo);
				iv_image.setImageBitmap(logo);
				iv_clean_img.setVisibility(View.GONE);
				mItemPicService.ImageDelete(String.valueOf(listitem.get(
						listAdapter.GetSelectedIndex()).getUpc()));
				int index = listAdapter.GetSelectedIndex();
				String upc = String.valueOf(listitem.get(index).getUpc());
				if (GlobalInfo.getInstance().isMGNetwork) {
					ItemPic itemPic = new ItemPic();
					itemPic.setUpc(upc);
					itemPic.setIp_image("");
					itemPic.setIp_image_sm("");
					mMGCreateFiles.createrFile(itemPic
							.toMGData("DELETE"));// UPDATE,DELETE
				}
				isImg = false;
				mDeviceManager.clearAllScannerBuffer();
				mDeviceManager.enableAllScanner();
			} else if (isImport) {
				ImportData();
			} else {
				mDeviceManager.disableAllScanner();
				mDeviceManager.disconnectAllScanner();
				mDeviceManager.resetALLDevices();
				finish();
			}
		}

		@Override
		public void onClickNo() {
			isDelete = false;
			isImg = false;
			isImport = false;
			mDeviceManager.clearAllScannerBuffer();
			mDeviceManager.enableAllScanner();
		}

		@Override
		public void onClickOK() {
			mDeviceManager.clearAllScannerBuffer();
			mDeviceManager.enableAllScanner();
		}

	};

	private TextWatcher itemwatcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			price_type = "1";
			SetPriceEnabledFalse();
		}
	};

	public void SetPriceEnabledFalse() {
		btn_price_setting_save.setEnabled(true);
		btn_price_setting_back.setEnabled(false);
	}

	public void SetPriceEnabledTrue() {
		btn_price_setting_save.setEnabled(false);
		btn_price_setting_back.setEnabled(true);
	}

	public OnClickListener onTextClickListener = new OnClickListener() {

		public void onClick(View view) {
			
			switch (view.getId()) {

			case R.id.et_st_date:
				if (GlobalInfo.getInstance().calendar_type) {
					mdssDialog.show(R.id.et_st_date,et_st_date.getText().toString());
				}else{
					ididDialog.show(R.id.et_st_date,et_st_date.getText().toString());
				}
				break;
			case R.id.et_st_time:
				if (GlobalInfo.getInstance().calendar_type) {
					tdssDialog.show(R.id.et_st_time,et_st_time.getText().toString());
				}else{
					itidDialog.show(R.id.et_st_time,et_st_time.getText().toString());
				}
				break;
			case R.id.et_et_date:
				if (GlobalInfo.getInstance().calendar_type) {
					mdssDialog.show(R.id.et_et_date,et_et_date.getText().toString());
				}else{
					ididDialog.show(R.id.et_et_date,et_et_date.getText().toString());
				}
				break;
			case R.id.et_et_time:
				if (GlobalInfo.getInstance().calendar_type) {
					tdssDialog.show(R.id.et_et_time,et_et_time.getText().toString());
				}else{
					itidDialog.show(R.id.et_et_time,et_et_time.getText().toString());
				}
				break;
			}

		}

	};
	
	private TextWatcher watcher2 = new TextWatcher() {

		public void afterTextChanged(Editable s) {
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			SetPriceEnabledFalse();
		}
	};

	Dialog DialogWindow = null;
	ListView lv_dialog_list;
	Button btn_dialog_ok, btn_dialog_cancel;
	List<MixMatch_detail> MMlist = null;
	MixMatchSelectionAdapter MMAdapter;
	int ScaleControlID;

	private void DialogWindows() {
		if (DialogWindow == null) {
			DialogWindow = new Dialog(this, R.style.dialog2);
			DialogWindow
					.setContentView(R.layout.price_mm_dialog_perview_models);
		}
		lv_dialog_list = (ListView) DialogWindow
				.findViewById(R.id.lv_dialog_list);
		btn_dialog_ok = (Button) DialogWindow.findViewById(R.id.btn_dialog_ok);
		btn_dialog_cancel = (Button) DialogWindow
				.findViewById(R.id.btn_dialog_cancel);
		lv_dialog_list.setOnItemClickListener(onItemClickDialogWindowListener);
		btn_dialog_ok.setOnClickListener(OnClickDialogWindowListener);
		btn_dialog_cancel.setOnClickListener(OnClickDialogWindowListener);

		MMlist = mMixMatchSettingService.getmmdetaillist();
		if (MMAdapter == null) {
			MMAdapter = new MixMatchSelectionAdapter(this, MMlist);
			lv_dialog_list.setAdapter(MMAdapter);
		} else {
			MMAdapter.setSource(MMlist);
			MMAdapter.notifyDataSetChanged();
		}

		DialogWindow.show();
	}

	OnItemClickListener onItemClickDialogWindowListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			MMAdapter.ScrollToRow(position);
		}

	};

	OnClickListener OnClickDialogWindowListener = new OnClickListener() {

		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.btn_dialog_ok:
				if (MMlist.size() > 0) {
					String value = String.valueOf(MMlist.get(
							MMAdapter.GetSelectedIndex()).getMs_no());
					Button btn_ScaleControl = (Button) priceDialog
							.findViewById(ScaleControlID);
					btn_ScaleControl.setText(value);
				}
				DialogWindow.dismiss();
				break;
			case R.id.btn_dialog_cancel:
				DialogWindow.dismiss();
				break;
			}
		}

	};

	public void TareImageView(String tare) {
		if (tare.equals("No")) {
			tv_tare_background.setVisibility(View.GONE);
			lv_tare.setVisibility(View.GONE);
			btn_single_tare.setVisibility(View.GONE);
			iv_add.setVisibility(View.GONE);
			iv_del.setVisibility(View.GONE);
		} else if (tare.equals("Single")) {
			tv_tare_background.setVisibility(View.GONE);
			lv_tare.setVisibility(View.GONE);
			btn_single_tare.setVisibility(View.VISIBLE);
			iv_add.setVisibility(View.GONE);
			iv_del.setVisibility(View.GONE);
		} else if (tare.equals("Multiple")) {
			tv_tare_background.setVisibility(View.VISIBLE);
			lv_tare.setVisibility(View.VISIBLE);
			btn_single_tare.setVisibility(View.GONE);
			iv_add.setVisibility(View.VISIBLE);
			iv_del.setVisibility(View.VISIBLE);
		} else {
			tv_tare_background.setVisibility(View.GONE);
			lv_tare.setVisibility(View.GONE);
			btn_single_tare.setVisibility(View.GONE);
			iv_add.setVisibility(View.GONE);
			iv_del.setVisibility(View.GONE);
		}
	}

	public void SetTareSetting() {
		if (tareSettingList == null) {
			tareSettingList = new ArrayList<TareSetting>();
		} else {
			tareSettingList.clear();
		}
		tareSettingList = mTareSettingService.FindAll();
	}

	public void SetBottleDeposit() {
		if (bottleList == null) {
			bottleList = new ArrayList<BottleSetting>();
		} else {
			bottleList.clear();
		}
		bottleList = mBottleSettingService.FindAll();
	}
	
	public void SetPrinterSetting(){
		if(printerList == null){
			printerList = new ArrayList<PrinterSetting>();
		}else{
			printerList.clear();
		}
		printerList = mPrinterSettingService.FindAll();
		PrinterSetting pr = new PrinterSetting(0, "None", null, 0);
		printerList.add(0, pr);
	}

	@Override
	public void onDataEvent(Object obj) {
	}

	
	public void ControlFindId() {
		et_upc = (EditText) findViewById(R.id.et_upc);
		et_name = (EditText) findViewById(R.id.et_name);
		et_desc = (EditText) findViewById(R.id.et_desc);
		et_price = (EditText) findViewById(R.id.et_price_multple);
		et_price_2 = (EditText) findViewById(R.id.et_retail_sell_price);
		et_wt = (EditText) findViewById(R.id.et_unit_price_factor);
		btn_net_wt = (Button) findViewById(R.id.btn_unit_of_measure);
		btn_dep = (Button) findViewById(R.id.btn_dep);
		et_vdr = (EditText) findViewById(R.id.et_vdr);
		et_sub_dept = (EditText) findViewById(R.id.et_sub_dept);
		et_case_pack_size = (EditText) findViewById(R.id.et_case_pack_size);
		et_case_cost = (EditText) findViewById(R.id.et_case_cost);
		cb_follow_dept = (CheckBox) findViewById(R.id.cb_follow_dept);
		cb_tax_1 = (CheckBox) findViewById(R.id.cb_tax_1);
		cb_tax_2 = (CheckBox) findViewById(R.id.cb_tax_2);
		cb_tax_3 = (CheckBox) findViewById(R.id.cb_tax_3);
		cb_tax_4 = (CheckBox) findViewById(R.id.cb_tax_4);
		cb_tax_5 = (CheckBox) findViewById(R.id.cb_tax_5);
		cb_tax_6 = (CheckBox) findViewById(R.id.cb_tax_6);
		cb_no_discnt = (CheckBox) findViewById(R.id.cb_no_discnt);
		cb_food_stamp = (CheckBox) findViewById(R.id.cb_food_stamp);
		cb_wic = (CheckBox) findViewById(R.id.cb_wic);
		cb_cvv = (CheckBox) findViewById(R.id.cb_cvv);
		cb_bottle_deposit = (CheckBox) findViewById(R.id.cb_bottle_deposit);
		btn_tare = (Button) findViewById(R.id.btn_tare);
		btn_back = (ImageButton) findViewById(R.id.btn_back);
		btn_next = (ImageButton) findViewById(R.id.btn_next);
		btn_search = (Button) findViewById(R.id.btn_search);
		btn_add = (Button) findViewById(R.id.btn_add);
		btn_del = (Button) findViewById(R.id.btn_delete);
		btn_save = (Button) findViewById(R.id.btn_save);
		btn_undo = (Button) findViewById(R.id.btn_undo);
		btn_exit = (Button) findViewById(R.id.btn_exit);
		cb_active = (CheckBox) findViewById(R.id.cb_active);
		cb_loyalty = (CheckBox) findViewById(R.id.cb_loyalty);
		cb_scale_weight = (CheckBox) findViewById(R.id.cb_scale_weight);
		cb_age_ver = (CheckBox) findViewById(R.id.cb_age_ver);
		iv_price_setting = (ImageView) findViewById(R.id.iv_price_setting);
		iv_add = (ImageView) findViewById(R.id.iv_tare_add);
		iv_del = (ImageView) findViewById(R.id.iv_tare_del);
		tv_tare_background = (TextView) findViewById(R.id.tv_tare_background);
		btn_single_tare = (Button) findViewById(R.id.btn_single_tare);
		lv_tare = (ListView) findViewById(R.id.lv_tare);
		btn_bottle_deposit = (Button) findViewById(R.id.btn_bottle_deposit);
		btn_age_ver = (Button) findViewById(R.id.btn_age_ver);
		iv_photo = (ImageView) findViewById(R.id.iv_photo);
		al = (AbsoluteLayout) findViewById(R.id.al_one);
		al2 = (AbsoluteLayout) findViewById(R.id.al_two);
		et_search = (EditText) findViewById(R.id.et_search);
		tv_page = (TextView) findViewById(R.id.tv_page);
		scrollLayout = (ScrollLayout) findViewById(R.id.ScrollLayoutTest);
		sp_list = (Spinner) findViewById(R.id.sp_condition);
		list = (ListView) findViewById(R.id.lv_listitem);
		iv_tare_del = (BeepImageButton) findViewById(R.id.iv_tare_del);
		iv_tare_add = (BeepImageButton) findViewById(R.id.iv_tare_add);
		btn_import = (Button) findViewById(R.id.btn_import);
		cb_coupon = (CheckBox) findViewById(R.id.cb_coupon);
		cb_printer = (CheckBox) findViewById(R.id.cb_printer);
		cb_mult_coupon = (CheckBox) findViewById(R.id.cb_mult_coupon);
		btn_printer = (Button) findViewById(R.id.btn_printer);
		tv_send_to_printer = (TextView) findViewById(R.id.tv_send_to_printer);
	}

	@Override
	public void onCloseWithReturn(Class<? extends MoleQBaseDialog> pramClass, int viewId, String parm) {
		super.onCloseWithReturn(pramClass, viewId, parm);
		
		Calendar c1 = Calendar.getInstance();
		mYear = c1.get(Calendar.YEAR);
		mMonth = c1.get(Calendar.MONTH) + 1;
		mDay = c1.get(Calendar.DAY_OF_MONTH);
		String time = String.format("%02d", 00) + ":"
				+ String.format("%02d", 00);
		String time2 = String.format("%02d", 23) + ":"
				+ String.format("%02d", 59);
		switch (viewId) {
		case R.id.et_st_date:
			et_st_date.setText(parm);
			if (et_st_time.getText().toString().equals("")) {
				et_st_time.setText(time);
			}
			break;
		case R.id.et_st_time:
			et_st_time.setText(parm);
			if (et_st_date.getText().toString().equals("")) {
				et_st_date.setText(mYear + "-" + String.format("%02d", mMonth) + "-" + mDay);
			}
			break;
		case R.id.et_et_date:
			et_et_date.setText(parm);
			if (et_et_time.getText().toString().equals("")) {
				et_et_time.setText(time2);
			}
			break;
		case R.id.et_et_time:
			et_et_time.setText(parm);
			if (et_et_date.getText().toString().equals("")) {
				et_et_date.setText(mYear + "-" + String.format("%02d", mMonth) + "-" + mDay);
			}
			break;
		default:
			break;
		}
		
	}
	
	@Override
	public void onShowingMessageDlg(boolean isShowing) {
	}

	@Override
	public void onReturnValue(int what, Object obj) {
		// TODO Auto-generated method stub
//		Toast.makeText(ItemSettingActivity.this, what,
//				Toast.LENGTH_SHORT).show();
		switch (what) {
		case 0:
			dis = (ItemDiscountSetting) obj;
			btn_dis_link.setText(String.valueOf(dis.getDs_desc()));
			break;
		case MoleQConstants.DIALOG_AGE_INFO:
			AgeSetting mAge = (AgeSetting) obj;
//			switch (CurrentMode) {
//				case DEPARTMENT_MODE:
//				btn_age.setText(mAge.getAs_desc());
//					break;
//				case SUBDEPT_MODE:
//					btn_subdept_age.setText(mAge.getAs_desc());
//					break;
//				}
			btn_age_ver.setText(mAge.getAs_desc());
			btn_age_ver.setTag(mAge);
//			ls_age_no = String.valueOf(mAge.getAs_no());
			break;
		default:
			break;
		}
	}

	public void SetCouponStatus(boolean checked) {
		if (checked) {
			cb_scale_weight.setChecked(false);
			cb_age_ver.setChecked(false);
			cb_follow_dept.setChecked(false);
			cb_loyalty.setChecked(false);
			cb_bottle_deposit.setChecked(false);
			cb_follow_dept.setEnabled(false);
			cb_scale_weight.setEnabled(false);
			cb_age_ver.setEnabled(false);
			cb_loyalty.setEnabled(false);
			cb_bottle_deposit.setEnabled(false);
			btn_tare.setEnabled(false);
			btn_single_tare.setVisibility(View.INVISIBLE);
			lv_tare.setVisibility(View.INVISIBLE);
			btn_bottle_deposit.setVisibility(View.INVISIBLE);
			iv_tare_del.setVisibility(View.INVISIBLE);
			iv_tare_add.setVisibility(View.INVISIBLE);
			tv_tare_background.setVisibility(View.INVISIBLE);
			iv_price_setting.setEnabled(false);
			btn_tare.setText("No");
		} else {
			if(cb_follow_dept.isChecked()){
				cb_scale_weight.setEnabled(false);
				cb_age_ver.setEnabled(false);
			}else{
				cb_scale_weight.setEnabled(true);
				cb_age_ver.setEnabled(true);
			}
			cb_follow_dept.setEnabled(true);
			cb_loyalty.setEnabled(true);
			cb_bottle_deposit.setEnabled(true);
			btn_tare.setEnabled(true);
			iv_price_setting.setEnabled(true);
		}
	}

	public void SetNetWTDataSource(String searchText) {
		if (NetWTList == null) {
			NetWTList = new ArrayList<NetWT>();
		} else {
			NetWTList.clear();
		}
		if (searchText.trim().equals("")) {
			NetWTList = mNetWTService.FindNetWT();
		} else {
			NetWTList = mNetWTService.FindNetWT(searchText);
		}
	}
}